简体   繁体   English

如何用相机角度移动相机?

[英]How to move the camera with the camera angle?

I made a simple threeJS 3d app in which you can look around and move with 4 keys.我制作了一个简单的threeJS 3d应用程序,您可以在其中环顾四周并使用4个键移动。 The problem is that it moves in the same direction no matter where you look to, obviously because I use:问题是无论你往哪里看,它都朝着同一个方向移动,显然是因为我使用:

camera.position.x += 0.1

You have to set the default displacement of (0.1, 0, 0) to a Vector3, then apply the camera's rotation (its quaternion) to that vector before adding it to its position.您必须将(0.1, 0, 0)的默认位移设置为 Vector3,然后在将其添加到其位置之前将相机的旋转(其四元数)应用于该向量。 See the code below:请参阅下面的代码:

// Create camera
var camera = new THREE.PerspectiveCamera();

// Create displacement vector to re-use
var dispVector = new THREE.Vector3();

function onRightKey() {
    dispVector.set(0.1, 0, 0); // Right key moves 0.1 on x axis
    applyDisplacement();
}

function applyDisplacement() {
    // We apply the camera's rotation to the displacement vector
    dispVector.applyQuaternion(camera.quaternion);

    // Move the camera position by the resulting displacement vector
    camera.position.add(dispVector);
}

You can apply this same idea to the other keys: (-0.1, 0, 0) if you want to move left, or (0, 0.1, 0) if you want to move up, etc:您可以将相同的想法应用于其他键: (-0.1, 0, 0)如果您想向左移动,或者(0, 0.1, 0)如果您想向上移动,等等:

function onLeftKey() {
    dispVector.set(-0.1, 0, 0); // Left key moves -0.1 on x axis
    applyDisplacement();
}

function onUpKey() {
    dispVector.set(0, 0.1, 0); // Left key moves 0.1 on y axis
    applyDisplacement();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM