I have developed a keyboard control function using Three.js that functions correctly when the camera is facing north, east, or west. However, when it turns to face south, southeast, or southwest, the controls become reversed.
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 help you better understand the issue I've been encountering, please visit my website through this link. My hypothesis is that the sine and cosine values may reverse after a 180-degree rotation.