2017-06-12 66 views
0

我正在創建一個賽車遊戲,我希望我的車左右移動一點旋轉 這是我迄今爲止所做的,但問題是當鍵是按下物體旋轉,但 不會回到原來的旋轉,我想要的是,當按下鍵時,它應該旋轉,但按下按鍵一秒後,它應該返回到其原始旋轉。 這裏是劇本我至今..返回對象旋轉後的x時間量的原始旋轉

using UnityEngine; 
using System.Collections; 

public class CarKeyboardMovement : MonoBehaviour { 

    public GameObject car; 
    public GameObject vehicle; 
    public float turnSpeed = 20f; 

    private bool spinning = false; 


    public float speed = 20; 

    Quaternion originalRotation; 

    public bool restorerotation = false; 
    public float timer = 0.0f ; 
    public float xtimer = 0.0f; 
    public float limittimer = 1f; 


    void Start() {  
     originalRotation = vehicle.transform.rotation;  

    } 

    // Update is called once per frame 
    void Update() { 
     if (Input.GetKey (KeyCode.Z) && !spinning) { 
      car.transform.Translate (Vector3.left);    

      vehicle.transform.Rotate (Vector3.up, speed * Time.deltaTime); 
      timer -= Time.deltaTime; 
      timer +=Time.deltaTime; 
      restorerotation =true; 
      if(restorerotation && limittimer < timer) 
      { 
       vehicle.transform.Rotate (Vector3.up, -speed * Time.deltaTime); 

       if(transform.rotation == originalRotation) 
       { 
        restorerotation = false; 
        timer = 0f; 
       } 
      } 
     } 
     if (Input.GetKey (KeyCode.V)&& !spinning) { 

      car.transform.Translate (Vector3.right); 
      vehicle.transform.Rotate (Vector3.up, -speed * Time.deltaTime); 
      timer -= Time.deltaTime; 
      timer +=Time.deltaTime; 
      restorerotation =true; 
      if(restorerotation && limittimer < timer) 
      { 
       vehicle.transform.Rotate (Vector3.up, speed * Time.deltaTime); 

       if(transform.rotation == originalRotation) 
       { 
        restorerotation = false; 
        timer = 0f; 

       } 
      } 
     } 
    } 

回答

0

你的代碼中有多個邏輯錯誤,這些都需要加以固定。這是我在查看代碼約45秒後注意到的。

spinning是無所事事的你,它總是假的(你永遠不會設置spinning爲true),所以!spinning始終是真實的。 condition && true簡化爲condition

limittimer同樣無所事事的你,你永遠不其值設置爲大於1同樣timer以外的任何始終是0:將其設置爲0,則每幀而輸入收到你添加然後的DeltaTime:

 timer -= Time.deltaTime; 
     timer += Time.deltaTime; 

所以timer的價值不會改變,並limittimer < timer1 < 0)始終是假的。

但是它並不重要,因爲此代碼(它應該在回到原始旋轉後阻止對象旋轉)不會被稱爲,除非用戶正在按特定覆蓋的鍵 「返回原來的」行爲。

xtimer從來沒有使用過。