Simplest way to rotate vector by Euler angles

Hi again!

So I’ve always wondered if there was a simpler way to rotate a vector by Euler angles (for example to make moveWithCollisions behave like Space.LOCAL) than the Rube Goldberg contraption I like to use:

const vec = new Vector3(0, 0, velocity);
const quat = Quaternion.FromEulerAngles(0, mesh.rotation.y, 0);
let mat = Matrix.Zero();
quat.toRotationMatrix(mat);
const newVec = Vector3.TransformCoordinates(vec, mat);
mesh.moveWithCollisions(newVec);

I do this because neither Vector3.rotateByEulerAngles nor Matrix.FromEulerAngles are a thing.

It works and is still pretty fast, but is there any simpler way I’ve simply overlooked? Of course you can tuck it in a function, but it still bothers me somehow. There must be a better way to go about it, right?

edit: and of course you can build the rotation matrix yourself, with sines and cosines (IIRC), but that’s not really simpler!

A little shorter to use

const vec = new Vector3(0, 0, velocity);
const quat = Quaternion.FromEulerAngles(0, mesh.rotation.y, 0);
let vec2 = Vector3.Zero();
vec.rotateByQuaternionToRef(quat, vec2);
3 Likes

Thank you! I was so focused on matrices I didn’t realize the ~Quaternion did have the coveted FromEulerAngles method ;)~ edit: of course I meant the
rotateByQuaternionToRef of course.

They really want us to use quaternions, huh? Time to stop procrastinating and finally learn the math behind them then.

This may give you a start Euler Angles and Quaternions - Babylon.js Documentation

Thank you! But I meant working with quaternions directly, like this. Maybe for a space game where you can move in all three dimensions that could be very useful.

You can manipulate quaternions in BJS. Have you seen Quaternion - Babylon.js Documentation

Just to emphasise something a little different between terminolgy in the video you gave the link to and BJS

In BJS (and Wikipedia) quaternion has the form a + x i + y j +z k and not all quaternions are rotation quaternions.

A rotation quaternion should be a unit quaternion In the video it appears the term quaternion is restricted to one having a unit vector for its axis.

Here is an example with the quaternion randomized and normalized to produce a unit quaternion

https://www.babylonjs-playground.com/#1ST43U#163

1 Like