SFML community forums

Help => Graphics => Topic started by: noct27 on December 23, 2022, 08:13:18 am

Title: Quad and mouse click collisions are consistently 3 tiles off.
Post by: noct27 on December 23, 2022, 08:13:18 am
Hello, i'm having problems clicking on individual tiles in a VertexArray populated with quads.

I followed this [tilemap](https://www.sfml-dev.org/tutorials/2.5/graphics-vertex-array.php) to build my tilemaps.

Here is the code I use to click on a tile.

 sf::Vector2f p = win->mapPixelToCoords(sf::Vector2i(sf::Mouse::getPosition().x, sf::Mouse::getPosition().y));
 int x_pos = p.x / 32;
 int y_pos = p.y / 32;
 if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)){
        tilemap->m_vertices[( (x_pos-3) + (y_pos-3) * 16) * 4].color = sf::Color::Green;
}

Where my tile size is `32x32` and the tilemap is `16` tiles long in the x and y direction. Without doing `x_pos-3` and `y_pos-3` the the wrong tile gets highlighted. Wondering why it's off by 3 tiles?
Title: Re: Quad and mouse click collisions are consistently 3 tiles off.
Post by: kojack on December 23, 2022, 09:12:00 am
By default, getPosition works in desktop (screen) coordinates. If you aren't using a fullscreen window, the mouse coordinates will be off by a bit.
You can make the mouse position relative to the window by passing the window to getPosition().
See if this helps:
sf::Vector2f p = win->mapPixelToCoords(sf::Vector2i(sf::Mouse::getPosition(*win).x, sf::Mouse::getPosition(*win).y));
Title: Re: Quad and mouse click collisions are consistently 3 tiles off.
Post by: noct27 on December 23, 2022, 08:39:48 pm
That was it, thanks!