SFML community forums

Help => Window => Topic started by: MickeyKnox on June 26, 2020, 02:20:56 am

Title: [SOLVED] How to select a Sprite from Mouse position?
Post by: MickeyKnox 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?
Title: Re: How to select a Sprite from Mouse position?
Post by: Laurent 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?).
Title: Re: How to select a Sprite from Mouse position?
Post by: MickeyKnox 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!