如何获得参考点击sf::CircleShape

How to get reference to clicked sf::CircleShape?

本文关键字:sf CircleShape 何获得 参考      更新时间:2023-10-16

在我的SFML程序中,我将绘制的CircleShapes存储在矢量中。如何得到参考一个点击鼠标按钮?

SFML中没有shape.makeClickable()函数,您所要做的就是:

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;
}

在你的类中使用这个向量:

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

编辑
获取你点击过的所有圆圈,而不仅仅是它找到的第一个圆圈:

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;
}