【问题标题】:How do you access each shape/object individually in SFML for C++如何在 SFML for C++ 中单独访问每个形状/对象
【发布时间】:2020-05-24 22:20:45
【问题描述】:

我正在寻找一种使用 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;
}

【问题讨论】:

  • 那是因为你只有一个形状,你在几个位置绘制。相反,每个“绘制的形状”需要 1 个形状,因此每个形状都可以有自己的颜色和位置。
  • @laancelot 你是否建议使用类似 std::vector<:rectangleshape shape> bundle_of_shapes;所以有很多形状?
  • sf::RectangleShape 对象的向量绝对是一个好的开始。

标签: c++ sfml


【解决方案1】:

按照 cmets 中的建议,您只创建一个 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();

【讨论】:

    猜你喜欢
    • 2014-02-13
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2014-01-28
    • 1970-01-01
    相关资源
    最近更新 更多