SFML:当我按下一个键时,图像被绘制并移动,但当我尝试创建它们的矢量时,图像不会移动

SFML: image gets drawn and moves when I press a key, but doesn't move when I try to create a vector of them

下面的代码有效...基本上当我按下空格键时,它会画一条线,在屏幕上沿 Y 方向不断移动。

// <Code that initializes window>


// set the shape
sf::CircleShape triangle(50, 3);
triangle.setPosition(300, 500);

sf::RectangleShape line;

// Start the game loop
while (window.isOpen())
{
    window.clear(sf::Color::White);
    // Process events
    sf::Event event;

    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
            line.setSize(sf::Vector2f(100,3));
            line.setRotation(90);
            line.setPosition(triangle.getPosition());
        }
    }

    // Clear screen

    window.clear();
    line.move(0, -0.1);
    window.draw(line);
    window.draw(triangle);

    // Update the window
    window.display();
}

问题是我一次只能画一条线,每次按空格键我都想画多条移动线。因此,我尝试创建一个线对象向量。但是,在绘制线条时,线条不会像前面的代码那样在 Y 方向上移动。

// set the shape
sf::CircleShape triangle(50, 3);
triangle.setPosition(300, 500);

sf::RectangleShape line;
std::vector<sf::RectangleShape> laserStack;

while (window.isOpen())
{
    window.clear(sf::Color::White);
    // Process events
    sf::Event event;

    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
            line.setSize(sf::Vector2f(100,3));
            line.setRotation(90);
            line.setPosition(triangle.getPosition());
            laserStack.push_back(line);
        }
    }

    // Clear screen

    window.clear();
    
    for (sf::RectangleShape l : laserStack) {
        l.move(0, -0.3);
    }

    for (sf::RectangleShape laser : laserStack) {
        window.draw(laser);
    }
    window.draw(triangle);

    // Update the window
    window.display();
}

(下图画出了线条,但没有移动)

我不明白为什么第一个代码行得通,线向上移动而第二个代码却行不通...看起来它们应该是等价的?

在线条上迭代时,您创建矩形的副本,然后移动这些副本,而不是存储在向量中的实例。

在 for-range 循环中使用引用。

for (sf::RectangleShape& l : laserStack) {
  l.move(0, -0.3);
}

for (sf::RectangleShape& laser : laserStack) {
  window.draw(laser);
}