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.

You can follow and like us:

Author: Horațiu Condrea

My name is Horațiu Condrea, and I work as a Software Developer Manager at Siemens PLM Software. I hope that my experiments will prove to be useful for many of you guys/girls out there. Don’t forget to leave a comment whenever you run over a bug or something that is not working as it should be. For any kind of information contact me.

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

  1. This code can be simplified to:

    bool lf_bCheckForMouseTrigger(sf::Sprite &av_Sprite, sf::RenderWindow &av_Window)
    {

    int mouseX = sf::Mouse::getPosition(av_Window).x;
    int mouseY = sf::Mouse::getPosition(av_Window).y;

    if(mouseX > av_Sprite.getPosition().x && mouseX av_Sprite.getPosition().y && mouseY < ( av_Sprite.getPosition().y + av_Sprite.getGlobalBounds().height) )
    {
    if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
    return true;
    }
    return false;
    }
    return false;
    }

    …and it works just the same (at least for me).

    1. int mouseX = sf::Mouse::getPosition(av_Window).x;
      int mouseY = sf::Mouse::getPosition(av_Window).y;

      if(mouseX > av_Sprite.getPosition().x && mouseX av_Sprite.getPosition().y && mouseY < ( av_Sprite.getPosition().y +
      av_Sprite.getGlobalBounds().height) )

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.