如何使火车转向运动?

问题描述:

我正在尝试开发一种类似火车的游戏,其中玩家将沿预定轨道移动。而且我很难制作一个功能来沿着轨道转动和移动玩家。游戏中只有L和U转(90和180度),在FYI。所以我的问题是,你如何制作一个移动功能,让玩家转动并沿着他的轨道/轨迹移动,而不管速度如何(不同的速度设置会有不同类型的“列车”)和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下降(我在我的高端工作站上试过这个功能),这个函数也会被搞砸,因为delta时间每个tick都会有所不同。那么我该如何解决这个问题?

在此先感谢。

+0

很难看到究竟是不是工作。什么是意想不到的输出?两个观察结果:a)turnRate取决于速度,所以最好交给速度并让这个函数计算转弯速度。 b)dt必须通过保存下次调用该函数的当前时间来计算。然后你可以测量时差。 – Aziraphale

+0

您可以使用行进距离作为参数,以不同方式处理标题的计算。当您输入一个转弯时,通过在每个时间步长添加可变速度* dt来计算此转弯内总行驶距离。这也将产生一个独立于FPS的标题。 – Aziraphale

+0

a。是的,这是我的想法。但我不知道如何根据速度来计算turnRate。例如,我们有一个掉头轨道,基本上是一个半径为10米的半圈。如何计算列车的转弯率,例如,时速60公里/小时?还是100公里/小时?这甚至不使用基于FPS的变化的dt。湾我不确定我明白。如果你在说什么是dt,我很清楚delta时间到底是什么。我的意思是,当游戏运行时,例如20 FPS将是不同的,因为每个时钟周期为40 FPS。我如何将其纳入等式? –

turnRate度是速度/周* dt的* 360

周长为2 * PI *半径

对于20的固定FPS,你会得到DT = 0.05。小心你的100公里/小时的例子,半径只有10米,因为你在回合中只花了几滴蜱。根据你的代码示例,火车不再在赛道上也不足为奇:)

正如我在评论中所建议的那样,我会放弃turnRate概念并使用距离作为参数来计算角度在列车在特定时间点行驶。只需添加DT当前速度*的距离,然后

角=距离/周* 360

无需用turnRate拨弄,这将只是堆积在每个替所犯的错误。

这有帮助吗?

+0

我想我明白你的意思。我会尝试一下。我会考虑这个答案。谢谢。 –