Search code examples
c++sfmlgraphic

How to get reference to clicked sf::CircleShape?


In my SFML program I am storing drawn CircleShapes in a Vector. How to get reference to one on clicking mouse button?


Solution

  • There's no shape.makeClickable() function in SFML, all you have to do is:

    sf::CircleShape* onClick(float mouseX, float mouseY) {//Called each time the players clicks
        for (sf::CircleShape& circle : vec) {
            float distance = hypot((mouseX - circle.getPosition().x), (mouseY - circle.getPosition().y)); //Checks the distance between the mouse and each circle's center
            if (distance <= circle.getRadius())
                return &circle;
        }
        return nullptr;
    }
    

    With this vector in your class:

    std::vector<sf::CircleShape> vec;
    

    EDIT
    To get ALL circles that you have clicked-on, and not only the first one that it finds :

    std::vector<sf::CircleShape*> onClick(float mouseX, float mouseY) {//Called each time the players clicks
        std::vector<sf::CircleShape*> clicked;
        for (sf::CircleShape& circle : vec) {
            float distance = hypot((mouseX - circle.getPosition().x), (mouseY - circle.getPosition().y)); //Checks the distance between the mouse and each circle's center
            if (distance <= circle.getRadius())
                clicked.push_back(&circle);
        }
        return clicked;
    }