Three.js 第一人称漫游
时间: 2025-01-05 15:31:30 浏览: 5
### Three.js 实现第一人称视角漫游
为了实现在 Three.js 中的第一人称导航效果,通常会结合 `THREE.PointerLockControls` 和键盘事件监听来控制相机的移动和旋转。这使得用户能够通过鼠标和键盘操作来进行场景中的自由探索。
#### 初始化场景与相机设置
创建基本的渲染器、场景以及相机对象:
```javascript
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// 创建WebGLRenderer并调整大小适应窗口尺寸
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
```
#### 添加PointerLockControls控件
引入 `PointerLockControls` 来锁定用户的鼠标指针以便更好地模拟第一人称视角下的头部转动行为[^1]:
```javascript
import { PointerLockControls } from 'https://cdn.jsdelivr.net/npm/three@0.148/examples/jsm/controls/PointerLockControls.js';
let controls;
if ('pointerLockElement' in document || 'mozPointerLockElement' in document) {
controls = new PointerLockControls(camera, document.body);
const enterButton = document.getElementById('enterFullscreen');
enterButton.addEventListener('click', () => {
controls.lock();
});
controls.addEventListener('lock', () => {
console.log("Locked");
});
controls.addEventListener('unlock', () => {
console.log("Unlocked");
});
}
```
#### 键盘输入处理逻辑
定义按键状态变量用于跟踪哪些键被按下,并据此更新角色的位置或方向:
```javascript
const keysPressed = {};
window.addEventListener('keydown', event => {
switch(event.code){
case 'ArrowUp':
keysPressed['forward'] = true; break;
case 'ArrowDown':
keysPressed['backward'] = true; break;
case 'ArrowLeft':
keysPressed['left'] = true; break;
case 'ArrowRight':
keysPressed['right'] = true; break;
}
});
window.addEventListener('keyup', event => {
switch(event.code){
case 'ArrowUp':
delete keysPressed['forward']; break;
case 'ArrowDown':
delete keysPressed['backward']; break;
case 'ArrowLeft':
delete keysPressed['left']; break;
case 'ArrowRight':
delete keysPressed['right']; break;
}
});
```
#### 更新循环中应用运动变化
最后,在动画帧回调函数内根据当前按下的键改变摄像机位置:
```javascript
function animate() {
requestAnimationFrame(animate);
if (keysPressed.forward) moveForward();
if (keysPressed.backward) moveBackward();
if (keysPressed.left) strafeLeft();
if (keysPressed.right) strafeRight();
renderer.render(scene, camera);
}
function moveForward(){
// 前进逻辑...
}
function moveBackward(){
// 后退逻辑...
}
function strafeLeft(){
// 左移逻辑...
}
function strafeRight(){
// 右移逻辑...
}
```
上述代码片段展示了如何构建一个简单的基于Three.js 的第一人称视角控制系统。实际项目可能还需要考虑碰撞检测等功能以增强交互体验。
阅读全文