How do you make a clickable sprite in SFML?

Skiddzie picture Skiddzie · May 8, 2014 · Viewed 12.1k times · Source

I've been looking through the SFML documentation for making clickable sprites, but so far I haven't found anything. Do you guys think you could help me out?

Answer

sjaustirni picture sjaustirni · May 10, 2014

There is nothing like sf::ClickableSprite in SFML so far, and probably there will never be. (Current list of classes in SFML)

However, you can obtain this behavior with the sf::Sprite object and the events. The idea is simple - as soon as you get the sf::Mouse::isButtonPressed(sf::Mouse::Left) event, check if the mouse is in the sprite. If it is, perform the action. You can perform another action (maybe undo) when button is released.

There is sf::Sprite::getGlobalBounds() function which returns you the position and the dimensions of the sprite. There's also sf::Mouse::getPosition() function, which returns the current position of the mouse. You can use sprite.getGlobalBounds().contains(mousePos) to check whether the mouse is in the sprite.

If you're using views, you'll need to add the view's position to sf::Mouse::getPosition(window), since it gets the mouse position relative to window coordinates.

(thanks to Chaosed0 for additional notes.)