0
\$\begingroup\$

I try to rotate objects in the same direction as a reference object.

Normaly this would be easy:

object1.rotation = reference.rotation

But the same rotation can be expressed with different vectors:

(0, 45, 270) is the same as (0, 225, 90) 
(0, 0, 270) is the same as (0, 180, 90)

In my case the final rotation should account for this.

The reference object has a rotation of: (0, 45, 270)

Object1 Should Rotate from (0, 45, 270) to (0, 0, 270)

Object2 Should Rotate from (0, 225, 90) to (0, 180, 90)

enter image description here

How can i calculate this? Im using unity if this is any help.

\$\endgroup\$
1
\$\begingroup\$

If you know one start and end rotation, in this example, from (0, 45, 270) to (0, 0, 270), first calculate the rotation between the two. You can do that like this:

Quaternion startRot = Quaternion.EulerAngles(0, 45, 270);
Quaternion endRot = Quaternion.EulerAngles(0, 0, 270);
Quaternion betweenRot = endRot * Quaternion.Inverse(startRot)

Now, you can simply rotate anything by multiplying by betweenRot:

Quaternion startRot2 = Quaternion.Euler(0, 225, 90);
Quaternion endRot2 = startRot2 * betweenRot;

endRot2 should be equivalent to Quaternion.Euler(0, 180, 90).

\$\endgroup\$
  • \$\begingroup\$ I think this could be the right solution but something is still odd. Quaternion.FromToRotation() takes only Vector3 and no Quaternions. I replaced it. But if i try your example it doesn't end up in (0, 0, 270) or in (0, 180, 90) \$\endgroup\$ – Nut Nov 23 '16 at 20:22
  • 1
    \$\begingroup\$ The Quaternion rotation from start to end is betweenRot = endRot * Quaternion.Inverse(startRot) \$\endgroup\$ – DMGregory Nov 24 '16 at 0:34
0
\$\begingroup\$

I found the solution with help from @tyjkenn

Quaternion newRot = Quaternion.FromToRotation(
    object.transform.forward, 
    reference.transform.forward
);

object.transform.rotation = neRot * reference.transform.rotation;

A few important things with this:

  • Both object and reference need to be aligned with unity's forward and up axis. (forward is the blue Z axis, up is the green Y axis). You can change this in your modeling software or within a parent gameObject.
  • The order of quaternion multiplication matters. Its the same as changing the order of rotation matrices
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.