Update object state and axis whenever the rotation happened

Hi, I am doing some animation on four wheels of the car while pressing arrow keys on keyboard. I just add the event listener using following code

document.addEventListener( 'keydown', keyDown );
document.addEventListener( 'keyup', keyUp );
function keyDown(evt){
    switch(evt.keyCode){
         case 38:
              forward = 1;
              break;
         case 40:
              forward = -1;
              break;
         case 37:
              turn = 1;
              break;
         case 39:
              turn = -1;
              break;
    }
}

To create an animation like running of car, I just rotate all wheels along X axis with following code within animation loop function.
wheel.rotation.x +=0.2;
To create an animation like turning, I need to rotate the wheels in Y axis.

The Problem is, Once I rotate the wheel in an axis, then the next rotation is performing in the updated axis value only. So It affects the actual animation. Please have a look into the following video. I hope it will give clarification about my issue.
So, if the object’s axes being same after rotation too, then the issue can be solved

By rotating the wheel, you’re rotating a local coordinate system (you can add AxesHelper to the wheel object to see exactly what I mean.)

Two solutions that may help you:
(1) Place the wheel in a group (a “pivot”.) Rotate the wheel for the forward movement, rotate the pivot group for sideways movement.
(2) Use a Matrix4 or empty Object3D to calculate transformations without initial rotation applied:

const mock = new Object3D();
mock.rotateY(angleSideways);
mock.rotateZ(angleForward);

wheel.rotation.copy(mock.rotation);
2 Likes

Thank you so much @mjurczyk. I went with the first solution. It is working. Thank you so much.
:heart_eyes:

Another option is to use mesh.rotation.order = "YXZ"

1 Like

Thanks for your reply @prisoner849. Can you please explain what is this order . what actually this will do?

Sure: https://threejs.org/docs/index.html#api/en/math/Euler.order

1 Like

Thanks @prisoner849