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