2

我正在设置一个简单的演示来测试 FPS 的播放器控件。我让鼠标旋转相机,播放器可以用 WASD 移动。我的问题是我需要什么算法才能让玩家能够相对于相机所面对的方向左右移动?向前和向后移动的控件效果很好,但是我在尝试使左右运动正常工作时遇到了麻烦。

我正在使用 THREE.JS 和 PhysiJS(物理引擎)。

这是我下面的一段代码......

    // the direction the camera is pointing in
    var cameraLookVector = this.controls.getDirection(this.vDirection);         
                
    // Player Movement
    this.v = new THREE.Vector3(0,0,0);
    if(keyboard.pressed("W")) { // Move forward
        this.v.x -= cameraLookVector.x * (Player.SPEED * delta * this.q); // works great
        this.v.z -= cameraLookVector.z * (Player.SPEED * delta * this.q);
    }
    if(keyboard.pressed("A")) { // Move left
        // Sets position relative to the world and not the direction the camera is facing
        this.v.x -= Player.SPEED * delta * this.q;
        /* Tried this but it didn't work
        this.v.x -= Math.cos(cameraLookVector * (Math.PI/180)) * (Player * delta * this.q);
        this.v.z -= Math.sin(cameraLookVector * (Math.PI/180)) * (Player * delta * this.q);
        */
    }
    if(keyboard.pressed("S")) { // Move backward
        this.v.x -= cameraLookVector.x * (Player.SPEED * delta * this.q); // works great
        this.v.z -= cameraLookVector.z * (Player.SPEED * delta * this.q);
    }
    if(keyboard.pressed("D")) { // Move right
        // Sets position relative to the world and not the direction the camera is facing
        this.v.x += Player.SPEED * delta * this.q;
    }
    
    this.bodyMesh.setLinearVelocity(this.v);

左右控件设置玩家相对于世界的位置。例如,如果我按住“A”,播放器将开始向屏幕左侧移动,但如果我用鼠标旋转相机,播放器将移动到屏幕中。我希望玩家的左右位置相对于相机的方向更新,所以从玩家的角度来看,他们总是向左或向右扫射。

感谢您的任何帮助!

4

2 回答 2

4

计算向左或向右方向的向量的一种计算量较小的方法是使用cameraLookVector和恒定“向上”方向的叉积。这假设cameraLookVector永远不会与这个“向上”平行。

跨积图

在这张图片中,我们可以选择b向量作为相机的观察方向,a作为一个常量向上,以及a x b作为一个非单位向量在你想要的左扫射方向。

var vectorUp = new THREE.Vector3(0, 1, 0);


// Left vector
var coefficient = Player.SPEED * delta * this.q;

this.v.copy(new THREE.Vector3().crossVectors(vectorUp, cameraLookVector).normalize().multiplyScalar(coefficient));
于 2015-02-16T21:26:25.117 回答
0

做到这一点的方法是创建一个新的 Vector3 并根据 的旋转对其进行转换camera,我假设您可以通过编程方式访问它。

var coefficient = Player.SPEED * delta * this.q;

// Right vector
this.v.copy(new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion).multiplyScalar(coefficient));
于 2015-02-16T21:18:13.273 回答