Reputation: 971
I have a box in my A-Frame scene that I want to control with the keyboard. I want W, S, and arrow Up/Down to control forward and backward movement, and I want the A, D, and arrow Left/Right to rotate the box left or right.
I have managed to get the box to move back and forward and to get the box to rotate. The problem is that when the box has rotated, I want to be able to press the forward/backward keys to move it in its new direction, but right now it still moves back and forward in the original direction.
HTML
<a-entity id="rover" geometry="primitive: box" material="color: yellow" position="0 1 -3">
JS:
var up = false,
right = false,
down = false,
left = false;
document.addEventListener('keydown',press)
function press(e){
if (e.keyCode === 38 /* up */ || e.keyCode === 87 /* w */ || e.keyCode === 90 /* z */){
up = true
}
if (e.keyCode === 39 /* right */ || e.keyCode === 68 /* d */){
right = true
}
if (e.keyCode === 40 /* down */ || e.keyCode === 83 /* s */){
down = true
}
if (e.keyCode === 37 /* left */ || e.keyCode === 65 /* a */ || e.keyCode === 81 /* q */){
left = true
}
}
document.addEventListener('keyup',release)
function release(e){
if (e.keyCode === 38 /* up */ || e.keyCode === 87 /* w */ || e.keyCode === 90 /* z */){
up = false
}
if (e.keyCode === 39 /* right */ || e.keyCode === 68 /* d */){
right = false
}
if (e.keyCode === 40 /* down */ || e.keyCode === 83 /* s */){
down = false
}
if (e.keyCode === 37 /* left */ || e.keyCode === 65 /* a */ || e.keyCode === 81 /* q */){
left = false
}
}
function gameLoop(){
var rover = document.getElementById('rover');
var currentPosition = rover.getAttribute('position');
var currentRotation = rover.getAttribute('rotation');
var direction = new THREE.Vector3(0, currentRotation.y, currentPosition.z);
if (up){
rover.setAttribute("position", {x: 0, y: 1, z: (currentPosition.z - 0.1)});
}
if(down){
rover.setAttribute("position", {x: 0, y: 1, z: (currentPosition.z + 0.1)});
}
if(left){
rover.setAttribute("rotation", {x: 0, y: (currentRotation.y + 1), z: 0});
}
if(right){
rover.setAttribute("rotation", {x: 0, y: (currentRotation.y - 1), z: 0});
}
requestAnimationFrame(gameLoop)
}
requestAnimationFrame(gameLoop)
I'm trying to get a Direction Vector and use it somehow, but I'm quite stuck at the moment.
Upvotes: 0
Views: 1330
Reputation: 177
The basic problem is you're setting the object's position in world space instead of moving it along its own object space coordinates.
There are several ways to go about this, with the most straightforward being using Object3D's translate method, which moves an object along its normalized axes. Instead of setting attributes try calling
rover.translateZ(# of units)
Etc. etc. Also see:
Upvotes: 1