-1

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

nmw01223
  • 1,611
  • 3
  • 23
  • 40
  • Could you add a more direct question? Are you asking for an explanation of quaternion? Or are you asking someone to write all of the code you need to do what you want to do? It would help if you were a bit more specific in what you want from the community. Thanks! – Jee Jun 04 '20 at 01:27

2 Answers2

3

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}");
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Thanks very much, that is exactly what I needed. Tried it and it works. I can now see why quaternions are so useful - tried to do it with Euler angles and ran into gimbal lock all over the place. – nmw01223 Jun 05 '20 at 04:19
2

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.