Search code examples
javascriptthree.js3dcameratrigonometry

Move up and down using pointer lock controls THREE.js


I need to move up and down using three.js's pointerlockcontrols. I am looking for the same kind of movement as three.js's flycontrols, where the amount you move up and down is proportional to the direction you are looking in (ie. if your looking north-east, you move in the Y and Z directions at the same rate).

I tried:

    if(keys[38] || keys[87]){
        Controls.moveForward(playerSpeed);
        Camera.position.y += Math.cos(Camera.rotation.y) * playerSpeed;
    }

Where keys is just a object of all the keys and whether they are down, however this didn't give the appropriate behavior, as looking straight down also moved you forward a lot.

Has anyone ever accomplished or knows how to do this?


Solution

  • You can change the implementation of moveForward(distance) to this:

        moveForward(distance) {
            const camera = this.camera;
    
            _vector.copy(this.getDirection(_vector));
    
            camera.position.addScaledVector(_vector, distance);
        }
    

    The original implementation uses the camera's side- and up-vectors to calculate the one pointing in the forward direction -> this enables the intended movement in the xz-plane.

    My change just uses the already existing getDirection method and applies the travelled distance on the resulting vector.