第一人称游戏Three.js - 控制 - 移动相机

时间:2018-06-09 22:36:26

标签: three.js camera

我想用Three.JS制作第一人称3D游戏。控件是W A S D.我将键分配为向前移动(W),向后移动(S),向左移动(A)和向右移动(D)。 在这段代码中,我解释了控件背后的逻辑。三角洲' porpuse用于通知摄像机正在朝什么方向看,因此当它向前或向后移动时,它会朝那个方向移动。这就是我遇到问题的原因。

//variables
 var pi = Math.PI; //just because I use PI a lot
 //controls
 var moveForward = false;
 var turnLeft = false;
 var moveBackward = false;
 var turnRight = false;

 //direção
 var deltaZ = pi;
 var deltaX = 0;
 var increaseDeltaX = true;
 var increaseDeltaZ = false;

/*code adding the camera, the scene and eventListener for the keys. When the keys mentioned are clicked the corresponded var turns true*/


function animate() {

//clicking W
if (moveForward) {
    camera.position.z += deltaZ/pi;
    camera.position.x -= deltaX/pi;
    //I used delta/pi because if delta=pi camera.position.z will increase 1
}

//clicking S
if (moveBackward) {
    camera.position.z -= deltaZ/pi;
    camera.position.x += deltaX/pi;
}

//clicking D
if (turnRight) {
    camera.rotation.y += pi/300; //clicking 300 times will spin 180 degrees

    //deltaZ starts in pi and decreasing, it varies between pi and -pi
    if (increaseDeltaZ) {
        deltaZ += pi / 150; //150= 300/2; pi= 90 degrees = 180/2
    } else {
        deltaZ -= pi / 150
    }

    if (deltaZ >= pi) {
        increaseDeltaZ = false;
    } else if (deltaZ <= -pi) {
        increaseDeltaZ = true;
    }

    //deltaX starts in 0 and increasing, it varies between pi and -pi
    if (increaseDeltaX) {
        deltaX += pi / 150;
    } else {
        deltaX -= pi / 150;
    }

    if (deltaX >= pi) {
        increaseDeltaX = false;
    } else if (deltaX <= -pi) {
        increaseDeltaX = true;
    }

}

此代码效果很好。当我向右转,然后向前移动时,相机向右移动。问题是当我向左转动相机时。我试图反转计算,但是数值刚刚搞砸,增量超过pi,方向变得不正确。 我把什么放在if(左)?

0 个答案:

没有答案