c++ - 如何在 C++ 的 SFML 中单独访问每个形状/对象

标签 c++ sfml

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

#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();

关于c++ - 如何在 C++ 的 SFML 中单独访问每个形状/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61993125/

相关文章:

c++ - 尝试销毁 sf::Font 时出现段错误

c++ - 不允许转换为不可访问的基类

c++ - 构造 vector C++

c++ - 如何在 C++ 中计算大数?

c++ - std::function 参数是不完整的类型,不允许

c++ - OpenGL 在 Z 缓冲区和深度测试方面遇到问题

c++ - SFML 在多线程中失败

c++ - getLocalBounds 替代文本对象? (SFML)

c++ - C++ 静态类 : undefined symbols 的 Clang 链接错误

c++ - 为什么在连接调试器/IDE 后我的 STL 代码运行如此缓慢?