以下代碼有效...基本上,當我按下空格鍵時,它會畫一條線,該線在螢屏上的 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();
}
(下圖顯示線條被繪制,但它們不移動)。

我不明白為什么第一個代碼有效,并且行向上移動但第二個代碼不起作用......看起來它們應該是等價的?
uj5u.com熱心網友回復:
遍歷線條時,創建矩形的副本,然后移動這些副本,而不是存盤在向量中的實體。
在你的 for-range 回圈中使用參考。
for (sf::RectangleShape& l : laserStack) {
l.move(0, -0.3);
}
for (sf::RectangleShape& laser : laserStack) {
window.draw(laser);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/442158.html
