简体   繁体   中英

Understanding quaternions in Unity

Having some difficulty in understanding how to use rotation (represented as a quaternion) in Unity.

What I want to do is note the rotation of an object at some time, then find out its new rotation shortly later, and turn that into how many degrees (or radians) of rotation around the X, Y and Z axes in the world space have occurred.

I am sure it is simple enough....

You can get the difference between two Quaternion by using Quaternion.Inverse and * operator

First store the rotation in a field

private Quaternion lastRotation;

// E.g. at the beginning
private void Awake()
{
    lastRotation = transform.rotation;
}

and then somewhere later do eg

Quaternion currentRotation = transform.rotation;
Quaternion delta = Quaternion.Inverse(beforeRotation) * currentRotation;
// and update lastRotation for the next check
lastRotation = currentRotation;

and then you get the Euler axis angles representation using Quaternion.eulerAngles

var deltaInEulers = delta.eulerAngles;
Debug.Log($"Rotated about {deltaInEulers}");

One of reasons of quaternion usage in 3D software is "gimbal lock" avoidance. Euler angles does any rotation as 3 separate rotations around each 3 fixed axes - X, Y, Z. But Quaternion instead, does rotation around single axis, which is freely oriented in space. Quaternion.AngleAxis can give you this Vetor3 axis, and the rotation angle (actualy, quaternion consists of Vector3(X,Y,Z) and angle W, in general). So one quaternion rotation can be represented by several different euler rotations.

To do what you want, you need first to get quaternion, representing rotation difference, not the actual rotation. It can be done with Quaternion.FromToRotation , which uses transform's forward and up vectors as the input. Then you can use Quaternion.eulerAngles .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM