【发布时间】:2013-06-12 00:59:06
【问题描述】:
我正在尝试制作一个小行星克隆体,到目前为止,我已经让我的飞船飞起来了。但是它的速度也取决于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();
}
【问题讨论】:
-
可能是因为您将位置设置为速度?而不是速度到速度?这可能只是语义上的,但我想我还是会问。我正在查看代码,试图找出可能出了什么问题。我猜如果你根本不动的话,某处的东西会被设置为零。
-
确保你没有陷入无限循环:while (window.pollEvent(event))
-
是的,您不应该将位置设置为:newPosition.x = curPosition.x + (VelocityPerSec / dtSeconds)? Y方向也一样。另外:您的新速度不应该使用位置来计算......至少如果我的理解是正确的简单物理学。使用这个方程来计算你每帧的新速度: vf = vi + at 也许修正这个数学会阻止你的模拟表现得很奇怪。让我知道它是怎么回事,我可以制定一个答案,以便人们更容易找到和阅读。
-
@DeanKnight 确实,从语义上讲,名称是错误的,而且我的数学可能很糟糕,因为我在很长一段时间内没有做很多物理方面的事情。我稍微修改了代码,重命名了一些东西。速度衰减不像我认为的那样起作用,我不确定如何使它起作用(因为它现在不断执行并立即降低速度,使船保持原位)。
while (window.pollEvent(event))不会导致无限循环。 -
@DeanKnight
while(window.pollEvent(event))是SFML中处理事件的方式,不能无限循环。