i've implemented a threejs keyboard control function that works fine as long as the camera is facing north, east or west direction, when it turns south, south-east, or south-west the controls reverse themselves
if(controls["KeyW"]){ // w
camera.position.x -= Math.sin(camera.rotation.y) * player.speed;
camera.position.z -= -Math.cos(camera.rotation.y) * player.speed;
}
if(controls["KeyS"]){ // s
camera.position.x = Math.sin(camera.rotation.y) * player.speed;
camera.position.z = -Math.cos(camera.rotation.y) * player.speed;
}
if(controls["KeyA"]){ // a
camera.position.x = Math.sin(camera.rotation.y Math.PI / 2) * player.speed;
camera.position.z = -Math.cos(camera.rotation.y Math.PI / 2) * player.speed;
}
if(controls["KeyD"]){ // d
camera.position.x = Math.sin(camera.rotation.y - Math.PI / 2) * player.speed;
camera.position.z = -Math.cos(camera.rotation.y - Math.PI / 2) * player.speed;
}
if(controls["Space"]) { // space
if(player.jumps) return false;
player.jumps = true;
player.velocity = -player.jumpHeight;
}
}
to better help you understand the problem i've been facing here's a link to my website, my guess is that the sin and cos revserse their values after a 180 rotation
CodePudding user response:
well the mistake i was making was that i was using pointer controls for mouse navigation and keyboard triggers to move around, digged the docs a little and realised that i could use built in functions of PointerLockControls called moveForward
and moveRight
const mouseControls = new PointerLockControls(camera, renderer.domElement);
document.addEventListener( 'click', () => {
mouseControls.lock()
}, false)
const keysDown: any = {
"KeyW": 0,
"KeyA": 0,
"KeyS": 0,
"KeyD": 0,
}
document.addEventListener("keydown", ({ code }) => {
keysDown[code] = 1
})
document.addEventListener("keyup", ({ code }) => {
keysDown[code] = 0
})
function updateControls() {
const forwardDirection = keysDown["KeyW"] - keysDown["KeyS"];
const rightDirection = keysDown["KeyD"] - keysDown["KeyA"];
mouseControls.moveForward(forwardDirection * player.speed)
mouseControls.moveRight(rightDirection * player.speed)
}
////////main animation function
function animate() {
requestAnimationFrame( animate );
updateControls();
renderer.render( scene, camera );
};
animate();