- Home /
Add or substract two quaternions/rotations
Hi,
I'm trying to instantiate a shot in front of my ship, but with a custom rotation relative to my ship's local coordinates.
So I tried this:
Instantiate(shotPrefab, transform.TransformPoint(Vector3(x,y,z)), transform.rotation + Quaternion.Euler(x,y,z));
But I get this error:
BCE0051: Operator '+' cannot be used with a left hand side of type 'UnityEngine.Quaternion' and a right hand side of type 'UnityEngine.Quaternion'.
So it says I can't add two quaternions.
What's the best way to solve this problem?
Answer by Peter G · Jun 15, 2011 at 05:34 PM
Multiplying should give you the result you want.
transform.rotation * Quaternion.Euler();
Just adding an additional note: with quaternions, it matters which one is on the left-hand/right-hand side. The rotation on the left of the multiplication symbol is applied first, then then one on the right is applied.
Who would have thought it, that little "*" could solve all my grief! Thank you so much for helping me with my understanding of C#
Instantiate(asteroid[randomAsteroid], spawn[randomSpawn].transform.position, spawn[randomSpawn].transform.rotation * Quaternion.Euler(0, Random.Range(-90, 90), 0));
Had got so close before when i tried using "+" and that was about 3 hours, 5 API descriptions, 35 Unity Answer pages and a youtube tutorial or two ago.
Thanks again.
Answer by Cameron_SM · Mar 09, 2014 at 07:20 AM
I'm not sure why Peter G's response was voted as correct or voted up, it's simply wrong.
Multiplying a Quaternion by a vector returns another vector, and the vector you multiply by should be a direction vector (representing a direction from the origin), not a set of floats representing euler angles in degrees. The result of that multiply operation is that direction vector rotated by the Quaternion.
In order to add two quaternion rotations correctly you multiply them:
Quaternion newRotation = transform.rotation * otherTransform.rotation
To subtract you need to multiply by the inverse:
// Rotate back to the starting position
transform.rotation = newRotation * Quaternion.Inverse(otherTransform.rotation)
Alternatively, you can use Euler Angles and simply + (Add) or - (Subtract) the values then convert the result to a Quaternion.
@Cameron - Quaternion.Euler() returns a Quaternion, not a vector.
Peter's answer is correct. Both transform.rotation and Quaternion.Euler are quaternions. 2 quaternions multiplied together give you another quaternion (the one that represents their combined rotations).
Wow... 27 people up-voted this answer :|
I'm hoping it's because he demonstrated how to use Quaternion.Inverse() which answers the second part of the question.
Thank you ! It took me 2 days how to fix Rotation with this in 1 minute.