4
\$\begingroup\$

Game engines like Three.js, Ogre3d and Unity3d often don't provide a default rotate method on their vector class. You usually have to do something like:

rotated = vector.applyQuaternion(
    new Quaternion().setFromEuler(
        new THREE.Vector3(0,0,Math.PI)));

This is a little confusing for me, so I just define a rotate method. Is there a special reason for this?

\$\endgroup\$
  • \$\begingroup\$ I assume because Quaternions have 4 elements rather than 3. They are not exactly the same thing. Quaternions represent something else. They contain the values to rotate rather than the position in space. But not sure myself though. \$\endgroup\$ – Sidar Mar 31 '13 at 12:14
  • \$\begingroup\$ It's a bitch. What you can do is q * v * q^-1 to rotate a vector by the rotation quaternion q, where v is a quaternion with v.x,v.y,v.z, 0 (v being your vector). Creating that v and applying the multiplication and inverse everytime is a pain (I probably should just make a function for it !). If anyone has a reason why I shouldn't be rotating vectors like this, please tell me \$\endgroup\$ – Jeff Mar 31 '13 at 12:54
7
\$\begingroup\$

It seems that most engines do have those rotation methods.

XNA has one in it's Vector3 struct.

// Returns a new Vector3 that results from the rotation.
public static Vector3 Transform (
     Vector3 value,
     Quaternion rotation
)

three.js has the function exactly as you wrote it.

In Unity's case, their Vector3.Rotate() method might be internally implemented as a quaternion rotation. It accepts an arbitrary axis and angle, which is all that is required.

//a quaternion is...
[sin(angle / 2) * [axis], cos(angle/ 2)]

//which expands to a 4-vector like...
[sin( angle / 2 ) * axis_x, 
 sin( angle / 2 ) * axis_y, 
 sin( angle / 2 ) * axis_z, 
 cos( angle / 2 )
]

Regardless, there's no reason the function can't be implemented manually, as you said. You can wrap it in a helper if you want to. Game Engine Architecture by Jason Gregory has a thorough enough explanation of its implementation, but it does not attempt to prove the 4-dimensional math. It does prove that they are equivalent to Matrix rotations, while requiring fewer total multiplications.

\$\endgroup\$

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