我想用C++中的SFML库绘制5个矩形。 当我运行代码时,只画了3个矩形。 下面是部分代码。 声明了一个矩形数组,并使用for循环,我已经固定了该数组的大小。 while循环中的conditonal语句被执行了5次,但在我的窗口中只显示了3个矩形。 我的窗户的大小是800x1080。 我该怎么修好呢?
sf::RectangleShape rect[5] ; //Declaring an array of Rectangles
for(int i=0; i<5; i++) { // setting the size of Rectangles
rect[i].setSize(sf::Vector2f(20,20));
}
int i=0, j=50, l=0;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
if (l<5) {
rect[l].setPosition(i,j);
window.draw(rect[l]);
window.display();
l++;
i+=30;
}
}
您应该将if语句替换为在矩形上迭代并显示矩形的for循环。
您也可以在矩形初始化期间而不是每次主循环迭代期间设置矩形的位置。
不要忘记使用window.clear(SF::Color::Black)清除窗口。