如何让火车转弯?

时间:2017-10-04 09:01:52

标签: game-physics

我正在尝试开发一种类似火车的游戏,其中玩家将沿着预定的轨道移动。而且我在制作一个能够沿着轨道转动和移动播放器的功能时遇到了麻烦。在整个关卡中,游戏只有L和U转(90度和180度),仅供参考。所以我的问题是,你如何制作一个运动功能,让玩家转动并沿着他的轨道/轨迹移动,无论速度如何(将有不同类型的"火车"具有不同的速度设置)和FPS(设备会有所不同,因此FPS也会有所不同)。这是我到目前为止所做的:

/// <summary>
/// Rotate and translate each tick if we are turning.
/// This will be called each tick when we are at a junction and need to turn.
/// </summary>
/// <param name="dt"> The delta time in mili seconds. </param>
/// <param name="turnRate"> The turn rate each second in degree. + if CW, - if CCW. </param>
/// <param name="targetHeading"> The target angle in degree. Can be 0, 90, 180, 270. In world space coordinate. </param>
/// <param name="speed"> The speed of the train. </param>
void TurnAndMoveEachTick(float dt, float turnRate, float targetHeading, float speed)
{
    float currentHeading = getHeading();
    float nextHeading = currentHeading + turnRate * dt; //Get thenext  heading this tick

    //Clamp the turning based on the targetHeading
    if ( (turnRate > 0.0 && nextHeading > targetHeading) ||
         (turnRate < 0.0 && nextHeading < targetHeading)   )
        nextHeading = targetHeading;

    //Turn
    this.rotate(nextHeading, Coordinate::WORLD); //Rotate to nextHeading usng the world space coordinate.

    //Move
    float displacement = speed * dt;
    this.translateBy(getHeading(), displacement); //Translate by displacement with the direction of the new heading.
}

当我尝试使用不同的速度时,它会变得非常错误。所以我还必须相应地调整turnRate。但是有多少?那是我无法得到的。而且,我认为如果FPS下降(我在我的高端工作站上尝试过这个功能),这个功能也会被搞砸了,因为每个滴答的增量时间也会不同。那么我该如何解决这个问题呢?

提前致谢。

1 个答案:

答案 0 :(得分:1)

turnRate in degrees是速度/周长* dt * 360

周长为2 * pi *半径

对于20的固定FPS,你会得到dt = 0.05。小心你的100公里/小时和半径只有10米的例子,因为你只在转弯处花了几个蜱。根据您的代码示例,火车不再在轨道上就不足为奇了:))

正如我在评论中所建议的,我会丢弃turnRate概念并使用距离作为参数来计算列车在给定时间点行进的角度。只需将当前速度* dt添加到一个距离,然后

角度=距离/周长* 360

无需使用turnRate,只会累积每次滴答错误。

这有帮助吗?