我正在制作一个围绕图形移动的机器人 ARM ,但是当我尝试使用键盘旋转一个形状时,它会无限旋转:我希望它在我按下右箭头时只旋转一次。我该如何解决这个问题?
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();
}
最佳答案
现在,这条线
transform.rotate(ang, WIDTH / 2, HEIGHT / 2);
在程序的每一帧调用,因为它在主循环中,不断运行。如果您希望它仅在您的游戏检测到某些输入时发生,请将其放入您的事件轮询中,如下所示:
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;
}
}
}
否则你的 ARM 将无限期地继续旋转。
编辑:感谢@alseether 指出 Transform::rotate
函数将角度添加到形状的当前旋转。所以每次增加 ang
会逐渐使形状旋转得越来越快......如果你不想发生这种情况,只需将 ang
设置为一个常量值,它就会以恒定速率旋转立方体。
关于c++ - SFML 形状无限旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418179/