I'm making a robot arm which moves around a graph but when I try to rotate a shape with my keyboard it rotates infinetly: I want it to rotate just one time when I press the right arrow. How can I solve this?
Transform transform;
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
}
if (event.type == Event::KeyPressed)
{
switch (event.key.code)
{
case Keyboard::Right:
ang += 1;
}
}
window.clear(Color::White);
window.draw(braccio, transform);
transform.rotate(ang, WIDTH / 2, HEIGHT / 2);
window.draw(assi);
window.display();
}
Right now, this line
transform.rotate(ang, WIDTH / 2, HEIGHT / 2);
Is called on every frame of your program because it's in the main loop, that runs constantly. If you want it to happen only while your game detects some input, put it inside your event polling, like so:
while (window.pollEvent(event))
{
// Do your event handling in here, input, etc.
if (event.type == Event::Closed)
window.close();
// This event case should also be inside here.
if (event.type == Event::KeyPressed)
{
switch (event.key.code)
{
case Keyboard::Right:
transform.rotate(ang, WIDTH / 2, HEIGHT / 2);
break;
}
}
}
Otherwise your arm will continue to rotate indefinitely.
EDIT: Thanks @alseether for pointing out that the Transform::rotate
function adds the angle to the shape's current rotation. So incrementing ang
each time will gradually make the shape rotate faster and faster... If you don't want this to happen just set ang
to a constant value and it will rotate the cube at a constant rate.