SFML community forums

Help => General => Topic started by: eniddelemaj on July 25, 2016, 12:54:14 pm

Title: how to check collision with mouse?
Post by: eniddelemaj on July 25, 2016, 12:54:14 pm
        sf::Text text;
        text.setPosition(100, 100);
        text.setFont(font);
        text.setString("example");
        text.setColor(sf::Color::Green);

        sf::FloatRect collision = text.getLocalBounds();

        sf::Vector2f point = sf::Vector2f(100, 100);

       
        if (collision.contains(point))
        {
                text.setColor(sf::Color::Red);
        }
 
I want to check collision with mouse. so if i move with the cursor over the text that the text change its color to red. I didnt become smarter of the tutorials:/

the code works but there is no result

sorry for my english i hope you can help!
Title: Re: how to check collision with mouse?
Post by: G. on July 25, 2016, 01:01:21 pm
Use getGlobalBounds instead of getLocalBounds.
getLocalBounds ignores transformations (position etc.)
Title: Re: how to check collision with mouse?
Post by: eniddelemaj on July 25, 2016, 01:03:39 pm
i did but the same result:/
Title: Re: how to check collision with mouse?
Post by: Hapax on July 25, 2016, 01:28:00 pm
Are you using a view?
Title: Re: how to check collision with mouse?
Post by: eniddelemaj on July 25, 2016, 01:33:01 pm
no im just trying the codes of the tutorials
Title: Re: how to check collision with mouse?
Post by: Yohdu on July 25, 2016, 03:00:10 pm
Can you provide us with your entire code ? (with the game loop and everything...)

EDIT : looking at the code you already provided, the point you are testing is actually not the mouse position. It should be :

sf::Vector2f point = sf::Mouse::getPosition(window)
Title: Re: how to check collision with mouse?
Post by: Hapax on July 25, 2016, 09:08:07 pm
It looks like you're attemping to check to see if it's working by using values you are sure to be right by checking a point that's at the text's position, right?
Unfortunately, that's not correct as the text's actual position maybe (and probably is) off-set from this position; getGlobalBounds() gives you this information if you would like it (left and top).

For example, a part of the code you provided could be changed to this:
    sf::FloatRect collision = text.getGlobalBounds();
    sf::Vector2f point = sf::Vector2f(collision.left + 1.f, collision.top + 1.f); // I've added to make sure it's inside the bounds