簡體   English   中英

對象Unity的旋轉以錯誤的值旋轉

[英]Rotation of Object Unity rotating at wrong value

我的問題是我希望能夠旋轉一個圓柱9次。 360/9是40所以我應該做的就是旋轉40度9次。 然而,這不起作用,因為當我第一次旋轉圓柱而不是旋轉40度它旋轉39.99度時。 這也發生在其他輪換中。

我正在這樣做。

if(Input.GetKeyUp("i"))
      transform.GetChild(m_Section).Rotate(0,40.0f,0);

我有統一版本3.4它不是專業版我在C#編碼。

任何幫助,因為我剛開始嘗試學習團結。

Unity3D將旋轉存儲在一個名為quaternion的非常抽象的數學表示中。 從Euler角度到Euler角度的轉換(你在Unity編輯器中看到的)涉及一系列三角函數,因此容易出現舍入誤差,特別是對於簡單的浮點型。

為了解決這個問題,我建議在開始旋轉之前存儲初始的Quaternion對象,並在過程結束時設置它。 一些偽代碼:

public class RotationController : MonoBehaviour {
    Quaternion rotationAtStart;
    int numOfRotations = 0;

    void rotate () {
        numOfRotations++;
        if (numOfRotations == 1) {
            rotationAtStart = transform.rotation;
        } else if (numOfRotations < 9) {
            transform.Rotate (new Vector3 (0,40.0f,0));
        } else if (numOfRotations == 9) {
            transform.rotation = rotationAtStart;
        }
    }
    void Update () {
        if (numOfRotations < 9) {
            rotate ();
        }
    }
 }   

360°的特殊情況使這種方法穩定。 小於360°時,您必須承受小的舍入誤差。 對於這種情況,我建議計算目標四Quaternion.RotateTowardsQuaternion.RotateTowards並在最后一步設置它類似於360的情況。

另一個有用的東西是動畫 您可以將動畫定義為平滑或離散步驟,如果按下“i”,則只需調用GameObject.animation.Play("MyRotation") 在動畫終止時,最后使用AnimationEvent獲取通知。

最后Mathf包含一個函數近似處理浮點不精確的問題。

在這篇文章中看看Kungfooman的答案,他描述了旋轉超過90度或90度以及270度的問題。 他提供了一個擴展,它將始終為您想要設置的值計算Quaternion的正確懸垂。 看看這里:

using UnityEngine;
using System.Collections;

public class ExtensionVector3 : MonoBehaviour {

    public static float CalculateEulerSafeX(float x){
        if( x > -90 && x <= 90 ){
            return x;
        }

        if( x > 0 ){
            x -= 180;
        } else {
            x += 180;
        }
        return x;
    }

    public static Vector3 EulerSafeX(Vector3 eulerAngles){
        eulerAngles.x = CalculateEulerSafeX(eulerAngles.x);
        return eulerAngles;
    }
}

我用它是這樣的:

Quaternion newQuat = m_directionalLight.transform.rotation;
Vector3 nL = new Vector3(ExtensionVector3.CalculateEulerSafeX(xNewValueLight), 
                         0, 
                         0);
newQuat.eulerAngles = nL;

m_directionalLight.transform.rotation = 
     Quaternion.Lerp(m_directionalLight.transform.rotation, 
                     newQuat, 
                     Time.deltaTime);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM