Conversion between Euler <=> Quaternion like in Unity3d engine

后端 未结 4 1124
予麋鹿
予麋鹿 2020-12-17 04:38

I\'ve used two examples (from this site too), but results are not the same as those that said Unity.

Quaternion.Euler and .eulerAngles are Unity functions. FromQ doe

4条回答
  •  猫巷女王i
    2020-12-17 05:28

    This question is almost three years old, but I needed the same code and the ones posted here seemed to be incorrect, so I tweaked them and found this:

    public static Quaternion Euler(float yaw, float pitch, float roll) {
            yaw*=Mathf.Deg2Rad;
            pitch*=Mathf.Deg2Rad;
            roll*=Mathf.Deg2Rad;
    
            double yawOver2 = yaw * 0.5f;
            float cosYawOver2 = (float)System.Math.Cos(yawOver2);
            float sinYawOver2 = (float)System.Math.Sin(yawOver2);
            double pitchOver2 = pitch * 0.5f;
            float cosPitchOver2 = (float)System.Math.Cos(pitchOver2);
            float sinPitchOver2 = (float)System.Math.Sin(pitchOver2);
            double rollOver2 = roll * 0.5f;
            float cosRollOver2 = (float)System.Math.Cos(rollOver2);
            float sinRollOver2 = (float)System.Math.Sin(rollOver2);            
            Quaternion result;
            result.w = cosYawOver2 * cosPitchOver2 * cosRollOver2 + sinYawOver2 * sinPitchOver2 * sinRollOver2;
            result.x = sinYawOver2 * cosPitchOver2 * cosRollOver2 + cosYawOver2 * sinPitchOver2 * sinRollOver2;
            result.y = cosYawOver2 * sinPitchOver2 * cosRollOver2 - sinYawOver2 * cosPitchOver2 * sinRollOver2;
            result.z = cosYawOver2 * cosPitchOver2 * sinRollOver2 - sinYawOver2 * sinPitchOver2 * cosRollOver2;
    
            return result;
    }
    

    According to a few quick tests, this matches Quaternion.Euler 100%

提交回复
热议问题