I'm facing a tricky problem that I need help with. I am attempting to rotate a Cannon.Body based on mouse input, using the Three FPS example by Cannon as a demonstration of the issue.
Check out the code here View the GitHub repo here
When you run the code and activate pointerlockcontrols by clicking the "click to play" area, then press W for a second to bring the sphere into view of the camera, you'll notice that the sphere moves according to the WASD keys with velocity. Moving the mouse applies quaternion rotation to the Body, calculating proper velocity. However, after turning 180 degrees, the rotation on the X axis is somehow negated. When moving the mouse up, the sphere rotates down.
How can I resolve this issue? Could there be something else in the code interfering with the quaternion?
It might be worth noting that in the playercontroller (pl.js), I apply rotation to the sphereBody instead of the yaw- and pitchObjects.
Snippet from pl.js (Line 49):
var onMouseMove = function ( event ) {
if ( scope.enabled === false ) return;
var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
cannonBody.rotation.y -= movementX * 0.002;
cannonBody.rotation.x -= movementY * 0.002;
cannonBody.rotation.x = Math.max( - PI_2, Math.min( PI_2, cannonBody.rotation.x ) );
};
<p>And (Line 174):</p>
<pre><code>euler.x = cannonBody.rotation.x;
euler.y = cannonBody.rotation.y;
euler.order = "XYZ";
quat.setFromEuler(euler);
inputVelocity.applyQuaternion(quat);
cannonBody.quaternion.copy(quat);
velocity.x = inputVelocity.x;
velocity.z = inputVelocity.z;
In animate() function in codepen (Line 305):
testballMesh.position.copy(sphereBody.position);
testballMesh.quaternion.copy(sphereBody.quaternion);