我正在尝试制作一个小行星克隆,到目前为止,我已经让我的船飞起来了。但是它的速度也取决于FPS。因此,为了减轻这种情况,我已经读到我必须将我的控制变量与 deltaTime 相乘(如果我收集正确,则帧之间的时间)。但是,当我尝试实施时,船拒绝移动。我认为这是由于可能隐式舍入为 0(转换为 int?),但没有发出警告。我究竟做错了什么?
代码如下所示:
sf::Vector2f newPosition(0,0);
sf::Vector2f velocity(0,0);
float acceleration = 3.0f;
float angle = 0;
float angularVelocity = 5;
float velDecay = 0.99f;
sf::Clock deltaClock;
window.setFramerateLimit(60);
while (window.isOpen())
{
sf::Time deltaTime = deltaClock.restart();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed || ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
window.close();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
if(velocity.x < 10)velocity.x += acceleration * deltaTime.asSeconds();
if(velocity.y < 10)velocity.y += acceleration * deltaTime.asSeconds();
angle = player.getRotation() - 90;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
if(velocity.x > 0)velocity.x -= acceleration * deltaTime.asSeconds();
else velocity.x = 0;
if(velocity.y > 0)velocity.y -= acceleration * deltaTime.asSeconds();
else velocity.y = 0;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
player.rotate(-angularVelocity);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
player.rotate(angularVelocity);
}
newPosition.x = player.getPosition().x + (velocity.x * cos(angle * (M_PI / 180.0))) * deltaTime.asSeconds();
newPosition.y = player.getPosition().y + (velocity.y * sin(angle * (M_PI / 180.0))) * deltaTime.asSeconds();
player.setPosition(newPosition);
velocity.x *= velDecay;
velocity.y *= velDecay;
window.clear();
window.draw(background);
window.draw(player);
window.draw(debugText);
window.display();
}