2016-05-16 34 views
0

我正在創建協調程序,它在一段時間的過程中補間對象圍繞特定點旋轉。旋轉部分工作正常,唯一的問題是當我嘗試設置完美角度以避免萬向節鎖定時。如何在一個簡單的旋轉Tween中完善角度

protected bool _isRotating = false; 

/// <summary> 
/// Rotates the hand around a specific point 
/// </summary> 
/// <param name="point">The point to rotate around</param> 
/// <param name="perspective"> 
/// The perspective view in which the transform occurs, by default this is Camera.Main 
/// </param> 
public IEnumerator RotateHand(GameHelper.Axis axis, bool isPositiveDirection, 
           Vector3 isolatedRotationPoint, float inTime = 1f, 
           int degrees = GameHelper.RIGHT_ANGLE_DEGREES, 
           Transform perspective = null) 
{ 
    if (_isRotating) 
    { 
     yield break; 
    } 

    _isRotating = true; 

    var targetPerspective = perspective ?? Camera.main.transform; 

    int charge = isPositiveDirection ? 1 : -1; 
    int normalizedDegrees = degrees * charge; 

    var noralizedAxisVector = this.GetNormalizeHandVectors(axis, targetPerspective); 

    var perfectAngles = transform.eulerAngles +(noralizedAxisVector * normalizedDegrees); 


    float startTime = Time.time; 
    float endTime = startTime + inTime; 
    while (Time.time < endTime) 
    { 
     var delta = normalizedDegrees * (Time.deltaTime/inTime); 
     transform.RotateAround(isolatedRotationPoint, noralizedAxisVector, delta); 
     yield return null; 
    } 

    //correct end values for loss in floating point percision 
    transform.eulerAngles = perfectedAngles; 


    _isRotating = false; 
} 

這很奇怪,因爲在某些時候的目標完全正確旋轉,這應該意味着我有一些跡象翻轉,或者我的軸的關閉。這是根據您的主要視角對軸進行歸一化的功能。

protected Vector3 GetNormalizeHandVectors(GameHelper.Axis axis, Transform perspective) 
{ 
    var forward = perspective.transform.TransformDirection(Vector3.forward); 
    forward = forward.normalized; 

    switch (axis) 
    { 
     case GameHelper.Axis.X: 
     { 
      return perspective.transform.TransformDirection(Vector3.right); 
     } 
     case GameHelper.Axis.Y: 
     { 
      return perspective.transform.TransformDirection(Vector3.up); 
     } 
     case GameHelper.Axis.Z: 
     { 
      return perspective.transform.TransformDirection(Vector3.forward); 
     } 
    } 

    throw new Exception("Axis Not Found"); 
} 

有誰知道,我該如何設置合適的完美角度?

回答

2

不確定這是否適用於您的情況,但當使用Quaternions代替XYZ旋轉時,還可以解決萬向節鎖定問題。該課程提供角度軸旋轉和角度軸旋轉。

+0

我打算使用四元數我想通了如何旋轉,但我無法弄清楚如何圍繞一個點旋轉 –

+0

如果點在本地座標中給出(相對於你想旋轉的物體),這可以通過以下方式完成: 1.用點座標轉換; 2.使用四元數旋轉對象(使用AngleAxis方法和'normalizedAxisVector'作爲座標軸); 3.用負點座標來翻譯 – Fons

+0

我該如何計算? –