2014-06-17 91 views
0

Im試圖旋轉我的玩家面對最後一次點擊的位置。我已經很好地執行此操作,但是現在我想要以設定的速度旋轉播放器,而不是立即改變旋轉的精靈。 我試過了幾種我在網上找到的方法,但沒有一種適合我。這是我的東西統一:使用Lerp/Slerp圍繞Z軸旋轉物體

void Update() 
{ 
    if (Input.GetMouseButtonDown (0)) 
    { 

      Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; 
      diff.Normalize(); 
      float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg; 
      transform.rotation= Quaternion.Euler(0f, 0f, rot_z - 90); 


      Instantiate(ProjectilePrefab, transform.position, transform.rotation); 
     } 
} 

上面的代碼工作正常,但它不顯示任何移動。我試圖做到這一點,但位置是錯誤的,旋轉也是瞬間的:

Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; 
var newRotation = Quaternion.LookRotation(diff); 
newRotation.y = 0.0f; 
newRotation.x = 0.0f; 
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 30); 

ANy ideas?

回答

2

這裏有兩個問題。首先,只有在用戶按下鼠標按鈕後才調用Slerp函數。您必須將它移出if部件或使用協程。其次,Slerp預計將從01的浮點數指示進度,而不是timedeltaTime。涵蓋lerp功能的官方示例很糟糕,因爲使用time值僅在遊戲運行的第一秒內才起作用。

你需要像這樣

if (Input.GetMouseButtonDown (0)) { 
    // your other stuff here 
    float starTime = Time.time; 
} 
float t = Time.time - startTime; 
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, t); 

在一秒鐘後旋轉將完成。如果你想要更快或更慢,只需乘以t

0

我找到了答案。這就是我的工作方式

if (Input.GetMouseButtonDown (0)) { 
        target = Camera.main.ScreenToWorldPoint (Input.mousePosition); 
        rotateToTarget = true; 
        print ("NEW TARGET: " + target); 
      } 

      if (rotateToTarget == true && target != null) {        
        print ("Rotating towards target"); 


        targetRotation = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward); 
        targetRotation.x = 0.0f;//Set to zero because we only care about z axis 
        targetRotation.y = 0.0f; 

        player.transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, Time.deltaTime * rotationSpeed); 



        if (Mathf.Abs (player.transform.rotation.eulerAngles.z - targetRotation.eulerAngles.z) < 1) { 

          rotateToTarget = false; 
          travelToTarget = true; 
          player.transform.rotation = targetRotation; 
          print ("ROTATION IS DONE!"); 
        } 
      }