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

Author Topic: [SOLVED] How to select a Sprite from Mouse position?  (Read 131 times)

0 Members and 1 Guest are viewing this topic.

MickeyKnox

  • Newbie
  • *
  • Posts: 38
    • View Profile
[SOLVED] How to select a Sprite from Mouse position?
« on: June 26, 2020, 02:20:56 am »
This is basically what I'm doing:

auto mouse = sf::Mouse::getPosition(window);
if (sprite.getGlobalBounds().contains(mouse.x, mouse.y))
    ...
 

That doesn't work as expected. A few issues arose:

1. The sprite's global bounds rect left/top is ALWAYS 0:0, although its position is not. Is this the expected behaviour?

2. sf::Mouse::getPosition(sf::Window&) doesn't respect position of the View, it seems to be the same as  sf::Mouse::getPosition(). I'm running in Fullscreen.

No I guess I could get the game world mouse position by adding the View position manually. And maybe if I set left/top to the position of the Sprite I could ask if it contains the mouse then.

But before trying this, I want to ask: What is the canonical way to get the Sprite under the mouse given my scenario with a game world much bigger than the desktop?
« Last Edit: June 26, 2020, 09:01:50 pm by MickeyKnox »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32432
    • View Profile
    • SFML's website
    • Email
Re: How to select a Sprite from Mouse position?
« Reply #1 on: June 26, 2020, 08:29:23 am »
There's an important step missing in your code: the conversion of mouse position from window coordinates (pixels) to scene coordinates (view units).

See https://www.sfml-dev.org/tutorials/2.5/graphics-view.php#coordinates-conversions

Regarding the sprite bounds problem, there must be something wrong in your code, the top/left coordinates should not be zero for the global bounds (you're not calling getLocalBounds() in your actual code, right?).
Laurent Gomila - SFML developer

MickeyKnox

  • Newbie
  • *
  • Posts: 38
    • View Profile
Re: How to select a Sprite from Mouse position?
« Reply #2 on: June 26, 2020, 09:01:22 pm »
Thanks for the hint to Window::mapPixelToCoords().

I did use getGlobalBounds on the Sprites, but upon further investigation I realized that the Sprites I had drawn and the Sprites I called getGlobalBounds on were not the same instances. I'm using pointers now and all is good!
« Last Edit: June 26, 2020, 09:03:18 pm by MickeyKnox »