Quick Tip: How to check when a sprite is clicked in SFML 2.0

I saw that this is a common problem this days . So, this is just a function that returns true when a sprite is clicked , even if the window is moved. You can integrate this function in any project you want.

Thanks and Enjoy!

bool lf_bCheckForMouseTrigger(sf::Sprite &av_Sprite, sf::RenderWindow &av_Window)
{
     
    int mouseX = sf::Mouse::getPosition().x;
    int mouseY = sf::Mouse::getPosition().y;
     
    sf::Vector2i windowPosition = av_Window.getPosition();
 
    if(mouseX > av_Sprite.getPosition().x + windowPosition.x && mouseX < ( av_Sprite.getPosition().x + av_Sprite.getGlobalBounds().width + windowPosition.x)
        && mouseY > av_Sprite.getPosition().y + windowPosition.y + 30  && mouseY < ( av_Sprite.getPosition().y + av_Sprite.getGlobalBounds().height + windowPosition.y + 30) )
    {
        if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
        {
            return true;
        }
        return false;
    }
     
    return false;
 
}

Cya next time.

Comments(2)
  1. Chris January 24, 2014
    • Chris January 24, 2014

Leave a Reply

Your email address will not be published. Required fields are marked *


*

WordPress SEO