SFML community forums

Help => Graphics => Topic started by: steven_g on May 30, 2016, 10:44:37 pm

Title: Check if sf::RectangleShape contains mouse global bounds?
Post by: steven_g on May 30, 2016, 10:44:37 pm
Hi,
I want to check if an sf::Shape contains the mouse's global bounds (and if left mouse button is clicked), and created the function below:
bool isRectClicked(sf::RectangleShape &rect, sf::RenderWindow &window) {
        sf::IntRect rect(rect.getPosition().x, rect.getPosition().y, rect.getGlobalBounds().width,  
        rect.getGlobalBounds().height);
        if (rect.contains(sf::Mouse::getPosition(window)) && (sf::Mouse::isButtonPressed(sf::Mouse::Left))) {
                return true;
        }
        return false;
}
 

However it says sf::RectangleShape has no member contains. How would I do this or do I have to do it the longer way by checking if the cursor is within the shape dimensions?
Title: Re: Check if sf::RectangleShape contains mouse global bounds?
Post by: G. on May 30, 2016, 11:04:40 pm
You should avoid calling 2 different variables with the same name.
"sf::RectangleShape &rect" and "sf::IntRect rect"
Title: Re: Check if sf::RectangleShape contains mouse global bounds?
Post by: Laurent on May 30, 2016, 11:18:29 pm
Why don't you just use rect.getGlobalBounds() directly anyway?
Title: Re: Check if sf::RectangleShape contains mouse global bounds?
Post by: Hapax on June 02, 2016, 12:42:57 am
Remember to map the mouse position into the view's co-ordinates (http://www.sfml-dev.org/tutorials/2.3/graphics-view.php#coordinates-conversions).

"Luckily" that returns a Vector2f so you can easily check to see if the rectangle shape's global bounds contains that point.

(click to show/hide)