尝试绘制存储在数组中的矩形,但只出现一个矩形?

  • 本文关键字:一个 存储 绘制 数组 c++ sfml
  • 更新时间 :
  • 英文 :


我的代码在这里:

如上所述,我正在尝试在屏幕上绘制一系列具有不同 x 位置的条形图,并将它们存储在数组中。似乎代码只绘制 1 个矩形,即使我已经检查过并且每个条都有不同的 x 位置,所以我确定这是我绘制对象的方式有问题,但感觉正确。 我还制作了一个类似的程序,其中包含使用相同的循环进行绘制的向量,但使用 .at(i( 代替,这确实有效,但奇怪的是这不起作用。

我一直在试图解决这个问题一段时间,我现在很累,所以请帮忙,指出我的错误......等。。。

#include <SFML/Graphics.hpp>

int main()
{
sf::RenderWindow window(sf::VideoMode(640, 640), "Square", sf::Style::Close | sf::Style::Resize);
sf::RectangleShape bar[64] = {sf::RectangleShape(sf::Vector2f( (window.getSize().x)/64.0f ,100.0f))};
// creates 64 bars of equal width 
for (int i = 0; i < 64; i++) 
{
bar[i].setFillColor(sf::Color(0, 0, 255, 255));
bar[i].setPosition( 10*i , (window.getSize().y)/2);
// sets bars x position to shift over for every bar
}
bar[3].setPosition(600, 300);
// just a test doesn't render even though it should
while (window.isOpen())
{
//////////////////////////////////////////////////
window.clear(sf::Color(130, 130, 150, 255));
for (int i = 0; i < 64; i++)
{
window.draw(bar[i]);
}
window.display();
/////////////////////////////////////////////////
}```

I cut out the rest of the code as the rest works and really has nothing to do with the code for simplicity sake
I want it to render out rectangles across the screen but it only displays one and I can't figure out why?

sf::RectangleShape具有默认的ctor:

sf::RectangleShape::RectangleShape  (   const Vector2f &    size = Vector2f(0, 0)   )   

您仅为第一个定义了矩形的大小,其他 63 个具有默认大小(0,0)

您可以将 rect 定义复制/粘贴到原始数组中,或者使用std::vector并调用 ctor 来获取元素的值和数量:

std::vector<sf::RectangleShape> bars( 64, // num of elems 
sf::RectangleShape( sf::Vector2f(window.getSize().x/64.0f ,100.0f) ) );

另一种解决方案是在循环的每次迭代中调用setSize(就像setFillColorsetPosition等一样(。

最新更新