【发布时间】: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对象的向量绝对是一个好的开始。