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 ....

1

2 Answers

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 e.g.

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}"); 
1

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy