您如何在 SFML for C++ 中单独访问每个 shape/object

How do you access each shape/object individually in SFML for C++

我正在寻找一种使用 SFML 使多个可点击矩形出现在用户屏幕上的方法。 我编写的代码仅适用于最后初始化的形状并更改所有方块的颜色。

#include <SFML/Graphics.hpp>
#include <iostream>


using namespace std;


int main()
{

    sf::RenderWindow window(sf::VideoMode(1280, 720), "warships");
    sf::RectangleShape shape(sf::Vector2f(50, 50));
    shape.setFillColor(sf::Color::Green);
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::Black);

        for (int i = 0; i < 10; ++i)
        {
            for (int j = 0; j < 10; ++j)
            {
                int x,y;
                y = 50 + 65 * i;
                x = 260 + 80 * j;
                shape.setPosition(x,y);
                window.draw(shape);
            }
        }

        if (shape.getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))) and event.type == sf::Event::MouseButtonPressed )
            shape.setFillColor(sf::Color::Yellow);

        window.display();
    }
return 0;
}

按照评论中的建议,您只创建一个 RectangleShape,然后更改它的位置。可能更好的主意是在代码的开头创建具有预定义位置的形状数组,如下所示:

std::vector<sf::RectangleShape> shapes;
for (int i = 0; i < 10; ++i)
{
    for (int j = 0; j < 10; ++j)
    {
        int x,y;
        y = 50 + 65 * i;
        x = 260 + 80 * j;
        shapes.push_back(sf::RectangleShape(sf::Vector(x, y)));
        shapes.back().setFillColor(sf::Color::Green);
    }
}

然后在你的绘图循环中简单地

window.clear(sf::Color::Black);

for (auto& shape : shapes)
{
    if (shape.getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window))) and event.type == sf::Event::MouseButtonPressed )
        shape.setFillColor(sf::Color::Yellow);

    window.draw(shape);
}

window.display();