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 backwards 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/backwards keys to move it in it's new direction, but right now it still moves back and forward in the original direction.
My 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. Any help would be appreciated.
Aucun commentaire:
Enregistrer un commentaire