The following code works... Basically when I press the spacebar, it draws a line, which continually moves in the Y direction on the screen.
// <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();
}
The issue is that I can only draw one line at a time, when I want to draw multiple moving lines everytime I press the spacebar button. Therefore I've tried to create a vector of line objects. However, while drawing the lines work, the lines don't move in the Y direction like the previous code.
// 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();
}
(Picture below shows that the lines get drawn, however they don't move).
I don't understand why the first code works, and the line moves upwards but the second code doesn't work... It seems like they should be equivalent?
When iterating over the lines, you create copies of the rectangles, and then move those copies, instead of the instances stored in the vector.
Use reference in your for-range loops.
for (sf::RectangleShape& l : laserStack) {
l.move(0, -0.3);
}
for (sf::RectangleShape& laser : laserStack) {
window.draw(laser);
}