I am learning C++/SFML and as a practice exercise I am making a small program that dispalys a 10x10 grid of 64x64 px square brown sprites in a window. This program allows you to select green/yellow/blue/grey/brown square sprites using the keyboard and replace any tile on said grid with this selected sprite. Game loop below:
while (window.isOpen())
{
window.clear(sf::Color(sf::Color::Black));
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1)) s_paintBrush = s_sand;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num2)) s_paintBrush = s_grass;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num3)) s_paintBrush = s_dirt;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num4)) s_paintBrush = s_water;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num5)) s_paintBrush = s_rock;
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
sf::Vector2i localPosition = sf::Mouse::getPosition(window);
int i = localPosition.x / x;
int j = localPosition.y / y;
if (i < columns && j < rows && i >= 0 && j >=0) grid[j][i].m_terrain = s_paintBrush;;
}
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
window.draw(grid[i][j].m_terrain);
grid[i][j].m_terrain.setPosition(x * j, y * i);
}
}
window.display();
}
"grid" is a 2D vector of the class "tile" that contains the sf::Sprite member variable "m_terrain" that stores the sprite to be displayed at the corresponding grid location. Integers x & y = 64 and are used to determine the coordinates of "grid" that correspond to the mouseclick location on the window. Anything with the prefix s_ is a sf::Sprite.
This program is working fine with one exception, when I press the left mouse button on a tile I want to change, the previous sprite disappears leaving a blank square area, and the replacement sprite displays in the top left corner of the window until the mouse button is released. The replacement sprite is then correctly displayed at the mouseclick location.
To me this indicates that the new sprite is being generated on mouseclick, but not receiving the setPosition coordinates until the mouse button is released. I am unsure how to fix this, and have not been able to find an answer (that is simple enough for me to understand at least, I am only learning!).
Thankyou for your attention.