如何相对于透视移动 ThreeJS 中的相机?

How can I move the camera in ThreeJS relative to perspective?

问题:

我一直在用 Threejs 开发第一人称迷宫游戏。我最近加入了 DeviceOrientationControls 以开始将其移向 VR,但我之前用于移动相机的系统与相机是分开的。相机不再随箭头键移动。


更新:

Alex Fallenstedt found a perfect example of what I wanted.

但是,我有一些问题;


资源:

How to control camera both with keyboard and mouse - three.js

Detecting arrow key presses in JavaScript

How to move camera along a simple path

How to control camera movement with up,down,left,right keys on the keyboard


比较

这是它之前的表现(有工作控制) http://orenda.ga/Whosebug/Nonvr.mp4

这是它现在的行为方式(使用方向) http://orenda.ga/Whosebug/VR.mp4


注: 我没有包含我的脚本,因为我认为这个问题不需要它。如果您需要,请询问,我会在这里插入。

回答你两个问题:

1) 脚本是如何让摄像机移动的?

让我们将脚本分解为它的基本原理。 The script begins by adding a bit of state to determine if the user is moving forward.. This state changes when the user interacts with W,A,S,D. We add event listeners that will change this state when a user presses a key or lifts up from a key.. Now, every single frame that is rendered, we can add velocity in specific directions depending on the state of what keys are pressed. This happens here。我们现在有了速度的概念。您应该在 animate() 中控制台记录速度值,并检查它在您四处移动时如何变化。

那么这个 velocity 变量实际上是如何移动相机的呢?嗯,这个剧本is also using an additional script called PointerLockControls. You can see the full script for PointerLockControls here. Notice how PointerLockControls' only argument is a camera. In order to move the camera, we need to use some nifty functions in PointerLockControls like getObject.。这个 returns 您传递给 PointerLockControls(又名相机)的 THREE.js 对象。

一旦我们可以获得相机,我们就可以通过将其 x、y 和 z 值转换为我们之前创建的 velocity in our animate function.. You can read more about translating objects with these methods in in the Object3D documentation.

来移动相机

2) 我如何简化这个 and/or 将其应用到我的工作中?

这可能是对相机实施第一人称控制的最简单方法。我之前与您分享的脚本示例中的所有其他内容都用于检查。就像用户在 threeJS 对象中一样,允许他们跳转。或者加一个concept of mass and gravity to always pull the user down after they jump. One thing that you might find very useful is to check if the pointer is in the browser's window!。举个例子,把它分解成最简单的组件,然后从那里构建。

这是一个代码笔示例,它向您展示了如何在没有指针锁定控件的情况下平稳地向前移动相机,从 line 53 https://codepen.io/Fallenstedt/pen/QvKBQo[=25= 开始]