Reputation: 80
I made a simple threeJS 3d app in which you can look around and move with 4 keys. The problem is that it moves in the same direction no matter where you look to, obviously because I use:
camera.position.x += 0.1
Upvotes: 2
Views: 260
Reputation: 28502
You have to set the default displacement of (0.1, 0, 0)
to a Vector3, then apply the camera's rotation (its quaternion) to that vector before adding it to its position. See the code below:
// Create camera
var camera = new THREE.PerspectiveCamera();
// Create displacement vector to re-use
var dispVector = new THREE.Vector3();
function onRightKey() {
dispVector.set(0.1, 0, 0); // Right key moves 0.1 on x axis
applyDisplacement();
}
function applyDisplacement() {
// We apply the camera's rotation to the displacement vector
dispVector.applyQuaternion(camera.quaternion);
// Move the camera position by the resulting displacement vector
camera.position.add(dispVector);
}
You can apply this same idea to the other keys: (-0.1, 0, 0)
if you want to move left, or (0, 0.1, 0)
if you want to move up, etc:
function onLeftKey() {
dispVector.set(-0.1, 0, 0); // Left key moves -0.1 on x axis
applyDisplacement();
}
function onUpKey() {
dispVector.set(0, 0.1, 0); // Left key moves 0.1 on y axis
applyDisplacement();
}
Upvotes: 1