javascripteventspointerlock

event.movement returning odd values


I have been playing around with webGL and I have reached a point I can make small three dimensional games with very pitiful graphics (it is more of a proof of concept/functionality as of now). For the three dimensional experience, it is nice to move the mouse in any direction infinitely and seamlessly to rotate the first person camera. Pointerlock allows me to lock and hide the cursor position, which is very helpful, but then I need to find another method of tracking the mouse's movements. In my research, event.movementX and event.movementY seemed to be the standard, but I often get large blips (usually between 500 and 583) of movement in the opposite direction of the mouse's movement. I tested this with numerous mice and trackpads and experience the same phenomenon.

Here are my relavent event listeners:

document.addEventListener("mousemove", function(event) {
   xMovement += event.movementX; 
   yMovement += event.movementY; 
   console.log(event.movementX)
}, false);

document.addEventListener("pointerlockchange", function(event) {
   if(pointerLockEnabled) pointerLockEnabled = false; 
   else pointerLockEnabled = true; 
   xMovement = 0; yMovement = 0; 
} , false);

And relevant render loop code:

function render() {
   if(pointerLockEnabled) {
       camera.rotation.y = -xMovement / 1000;
       camera.rotation.x = -yMovement / 1000;
       if(rightKey && !leftKey) {
          camera.position.x += 10 * Math.cos(camera.rotation.y);
          camera.position.z -= 10 * Math.sin(camera.rotation.y);
       }
       else if(leftKey && !rightKey) {
          camera.position.x -= 10 * Math.cos(camera.rotation.y);
          camera.position.z += 10 * Math.sin(camera.rotation.y);
       }
       if(upKey&& !downKey) {
          camera.position.z -= 10 * Math.cos(camera.rotation.y);
          camera.position.x -= 10 * Math.sin(camera.rotation.y);
       }
       else if(downKey && !upKey) {
          camera.position.z += 10 * Math.cos(camera.rotation.y);
          camera.position.x += 10 * Math.sin(camera.rotation.y);
       }
   }
}

But my console has occurrences such as this:

console capture

I added conditions to changing xMovement to prevent massive turns in camera angle, but I am still left with very annoying movement. Any ideas to patch or replace to a more seamless interface movement?


Solution

  • It could be helpful if you would throttle your mousemove event in some way. For example the lodash throttle version:

    function handleMouseMove(event) {
       xMovement += event.movementX; 
       yMovement += event.movementY; 
       console.log(event.movementX)
    }
    var throttledHandleMouseMove = _.throttle(handleMouseMove, 75);
    document.addEventListener("mousemove", throttledHandleMouseMove, false);
    

    With this approach handleMouseMove would not be executed more that 1 time per 75ms.