我有一個非常簡單的移動腳本附加到一個對象,允許我用動量向上,向下,向左或向右移動對象。昨晚我認爲劇本工作正常,沒有問題。我注意到物體有一些無限小的移動,但是由於物體簡單地畫在每一幀上而丟棄了它,或者由於代碼而使其「搖擺」。Unity C#Time.deltaTime錯誤
但是,今天我回到家後,把它開了火,物體立刻跳起來,向右邊移動得非常快。在經過一些調試之後,我感覺自己瘋了,因爲我沒有改變任何東西,所以我注意到我的筆記本電腦沒有插上電源,從而降低了機器的功率,並且讓我知道可能導致錯誤的原因。
我嘗試玩代碼,添加和刪除Time.Delta時間來改善它,但似乎無法讓問題消失。去除所有的Time.deltaTimes會讓它變得更糟糕,同時把它們放到任何地方都無法解決問題。
雖然時間問題導致我注意到問題,但我懷疑我的真正問題可能在我的移動代碼中,因爲即使我沒有按下按鈕,遊戲仍然在X和X上都記錄了一些速度Y軸讓我認爲它可能是if,else,else if語句的問題。
任何幫助,將不勝感激。
我的代碼如下:
float speedHorz = 0; //Horizontal starting speed.
float maxspHorz = 5; //Horizontal Max speed.
float speedVert = 0;
float maxspVert = 5;
float acceleration = 8; //How fast the object will reach maximum speed.
float deceleration = 12; //How fast the object will return to 0.
void Update()
{
playerMove();
}
public void playerMove()
{
//Up and Down, Acceleration
if ((Input.GetKey("s")) && (speedVert < maxspVert)) //If you press S and Verticl Speed is less than the max...
{
speedVert = speedVert - acceleration * Time.deltaTime; //Lower speed by acceleration, move down...
}
else if ((Input.GetKey("w")) && (speedVert > -maxspVert))
{
speedVert = speedVert + acceleration * Time.deltaTime;
}
//Up and Down, Deceleration
else
{
if (speedVert > deceleration * Time.deltaTime)
{
speedVert = speedVert - deceleration * Time.deltaTime;
}
else if (speedVert < deceleration * Time.deltaTime)
{
speedVert = speedVert + deceleration * Time.deltaTime;
}
else speedVert = 0 * Time.deltaTime;
}
//Left and Right, Acceleration
if ((Input.GetKey("a")) && (speedHorz < maxspHorz)) //If you are pressing the "a" key and speed is less than max speed...
{
//Move Left
speedHorz = speedHorz - acceleration * Time.deltaTime; //Accelerate negatively on the X axis, ie Move Left.
}
else if ((Input.GetKey("d")) && (speedHorz > -maxspHorz))
{
speedHorz = speedHorz + acceleration * Time.deltaTime;
}
//Left and Right, Deceleration
else
{
if (speedHorz > deceleration * Time.deltaTime)
{
speedHorz = speedHorz - deceleration * Time.deltaTime;
}
else if (speedHorz < deceleration * Time.deltaTime)
{
speedHorz = speedHorz + deceleration * Time.deltaTime;
}
else speedHorz = 0 * Time.deltaTime;
}
transform.position = new Vector2(transform.position.x + speedHorz * Time.deltaTime, transform.position.y + speedVert * Time.deltaTime);
}
可以調用Time.deltaTime嗎?如果是這樣,減速代碼不只是降低速度,而是將Min或Max放在上面,這樣負速度不會變成正值,反之亦然。 – Martheen