Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Quad and mouse click collisions are consistently 3 tiles off.  (Read 605 times)

0 Members and 2 Guests are viewing this topic.

noct27

  • Newbie
  • *
  • Posts: 3
    • View Profile
Quad and mouse click collisions are consistently 3 tiles off.
« 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?

kojack

  • Sr. Member
  • ****
  • Posts: 300
  • C++/C# game dev teacher.
    • View Profile
Re: Quad and mouse click collisions are consistently 3 tiles off.
« Reply #1 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));

noct27

  • Newbie
  • *
  • Posts: 3
    • View Profile
Re: Quad and mouse click collisions are consistently 3 tiles off.
« Reply #2 on: December 23, 2022, 08:39:48 pm »
That was it, thanks!