0
我在我的A-Frame場景中有一個框,我想用鍵盤控制。我想要W,S和上/下箭頭來控制向前和向後移動,並且我希望A,D和左/右箭頭向左或向右旋轉框。獲取A幀中實體的方向矢量
我設法讓箱子前後移動並使箱子旋轉。問題是當箱子旋轉時,我希望能夠按前進/後退鍵將其向新方向移動,但現在它仍然在原始方向上前後移動。
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)
我試圖得到一個方向向量,並以某種方式使用它,但我相當的時刻卡住。
完美的作品,非常感謝!必須首先將我的實體轉換爲一個對象,才能使它看起來很有效。 'var rover = document.getElementById('rover')。object3D;' – smuvv