2017-10-04 111 views
1

我正在嘗試開發一種類似火車的遊戲,其中玩家將沿預定軌道移動。而且我很難製作一個功能來沿着軌道轉動和移動玩家。遊戲中只有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。我如何將其納入等式? –

回答

1

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

周長爲2 * PI *半徑

對於20的固定FPS,你會得到DT = 0.05。小心你的100公里/小時的例子,半徑只有10米,因爲你在回合中只花了幾滴蜱。根據你的代碼示例,火車不再在賽道上也不足爲奇:)

正如我在評論中所建議的那樣,我會放棄turnRate概念並使用距離作爲參數來計算角度在列車在特定時間點行駛。只需添加DT當前速度*的距離,然後

角=距離/周* 360

無需用turnRate撥弄,這將只是堆積在每個替所犯的錯誤。

這有幫助嗎?

+0

我想我明白你的意思。我會嘗試一下。我會考慮這個答案。謝謝。 –