Has anyone found a way to rotate a CANNON.RigidBody object in CannonJS (the physics library)? I'm attempting to align the object's rotation with that of the camera, so they both face the same direction. I understand that I need to adjust the quaternion, but my current approach isn't yielding the desired results:
mPlayer.objectBody.quaternion.set(0, mPlayer.yawObject.rotation.y, 0, 1);
This code not only alters the rotation but also affects the Y-position of the object.
Check out the demo here where you can use the WASD keys to move the red rectangle that I'm trying to rotate.
You can view the main script here.
Currently, the object rotates automatically based on physics. Thank you for any assistance!
UPDATE:
I've made some progress in getting it to rotate properly. However, it doesn't complete a full 360-degree rotation and the angle is slightly off. If someone could take a look and identify what needs to be fixed, I would greatly appreciate it! :)
You can see the latest version at the same link as before, where the rectangle/body is positioned below the camera for better observation of the rotation accuracy.
Below is the additional code I added to enable rotation:
mPlayer.objectBody.quaternion.y = mPlayer.yawObject.rotation.y;
mPlayer.objectBody.quaternion.w = 1;
mPlayer.objectBody.quaternion.normalize();
In case you prefer not to sift through the code, note that mPlayer.yawObject.rotation.y
gets assigned within the MouseMove event as shown below:
var onMouseMove = function ( event ) {
var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
mPlayer.yawObject.rotation.y -= movementX * 0.002;
mPlayer.pitchObject.rotation.x -= movementY * 0.002;
mPlayer.pitchObject.rotation.x = Math.max( - PI_2, Math.min( PI_2, mPlayer.pitchObject.rotation.x ) );
};
Thank you once again for your assistance!