2016-08-17 36 views
0

我想根據用戶輸入(例如鍵盤左/右箭頭)旋轉一個對象(在一個軸上)。我正在用方法MoveRotation使用RigidbodyLerp vs tweening

所以在FixedUpdate,我使用Mathf.Lerp創建幀獨立角運動。

rotation = Mathf.Lerp(rotation, rotation + input, Time.deltaTime * speed) 

但這是線性的,我要順利完成這一旋轉(例如Sine.easeIn),所以它開始慢慢轉動,一段時間後,它的完全旋轉。

Unity中將補間與用戶輸入和幀獨立相結合的最佳方式是什麼? (我想我不能使用庫,例如​​DOTweeniTween因爲補間的時間是不知道。

+0

是否要在某個點上限旋轉或繼續加速?你也必須使用補間,或者你會考慮物理引擎嗎? –

+0

比方說,我想在某些時候(也用'tweening')來限制它,但是這個可補間的帽子並不是我主要關心的地方。我想使用純數學(但知道兩種解決方案都會很好) – MyFantasy512

+0

你檢查了我提供的答案嗎? – Programmer

回答

0

你可以使用Physics加快圍繞其軸的對象。

Rigidbody.AddTorque(torqueVector3, ForceMode.Accelerate); 

您將需要添加一個剛體對於這項工作,參數ForceMode設置爲加速其根據統一的文檔將:

添加一個連續加速到剛體,忽視了其質量

你可以添加一些代碼封頂速度,我認爲,這樣的:

if (Rigidbody.velocity.magnitude >= capAmount) 
{ 
    Rigidbody.velocity.magnitude = capAmount; 
} 

另一個更全局的方式來蓋的旋轉將是改變max angular velocity

+0

那麼使用自定義插值方法,而不是物理引擎? – MyFantasy512

0

所以它開始慢慢地旋轉,過了一段時間它就完全旋轉了 。

這可以用協程來完成。啓動協程並在while循環中執行所有操作。當按下左/右箭頭鍵時,有一個隨時間增加的變量,其中Time.deltaTime

public Rigidbody objectToRotate; 
IEnumerator startRotating() 
{ 
    float startingSpeed = 10f; 
    const float maxSpeed = 400; //The max Speeed of startingSpeed 

    while (true) 
    { 
     while (Input.GetKey(KeyCode.LeftArrow)) 
     { 
      if (startingSpeed < maxSpeed) 
      { 
       startingSpeed += Time.deltaTime; 
      } 
      Quaternion rotDir = Quaternion.Euler(new Vector3(0, 1, 0) * -(Time.deltaTime * startingSpeed)); 
      objectToRotate.MoveRotation(objectToRotate.rotation * rotDir); 
      Debug.Log("Moving Left"); 
      yield return null; 
     } 

     startingSpeed = 0; 

     while (Input.GetKey(KeyCode.RightArrow)) 
     { 
      if (startingSpeed < maxSpeed) 
      { 
       startingSpeed += Time.deltaTime; 
      } 
      Quaternion rotDir = Quaternion.Euler(new Vector3(0, 1, 0) * (Time.deltaTime * startingSpeed)); 
      objectToRotate.MoveRotation(objectToRotate.rotation * rotDir); 
      Debug.Log("Moving Right"); 
      yield return null; 
     } 
     startingSpeed = 0; 
     yield return null; 
    } 
} 

只需啓動協程Start()函數一次即可。它應該永遠運行。它將緩慢旋轉至快速,直到達到maxSpeed

void Start() 
{ 
    StartCoroutine(startRotating()); 
} 

可以修改startingSpeedmaxSpeed可變適合您的需要。如果您認爲達到maxSpeed的時間過長,則可以在將Time.deltaTime;添加到startingSpeed之後將其與另一個數字相乘。例如,將startingSpeed += Time.deltaTime;更改爲startingSpeed += Time.deltaTime * 5;