threejs实现漫游 代码
时间: 2023-07-24 15:25:02 浏览: 102
以下是一个简单的使用Three.js实现漫游的代码示例:
```javascript
// 初始化Three.js场景
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 添加一个地面
var groundGeo = new THREE.PlaneBufferGeometry(100, 100);
var groundMat = new THREE.MeshPhongMaterial({
color: 0xffffff,
specular: 0x050505
});
var ground = new THREE.Mesh(groundGeo, groundMat);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -1;
scene.add(ground);
// 添加一个立方体
var cubeGeo = new THREE.BoxBufferGeometry(1, 1, 1);
var cubeMat = new THREE.MeshPhongMaterial({
color: 0x00ff00,
specular: 0x050505
});
var cube = new THREE.Mesh(cubeGeo, cubeMat);
cube.position.y = 0.5;
scene.add(cube);
// 添加一个光源
var light = new THREE.PointLight(0xffffff, 1, 100);
light.position.set(0, 10, 0);
scene.add(light);
// 设置相机的初始位置和方向
camera.position.set(0, 1, -3);
camera.lookAt(new THREE.Vector3(0, 1, 0));
// 监听用户的键盘输入事件,控制相机的移动
var moveForward = false;
var moveBackward = false;
var moveLeft = false;
var moveRight = false;
var moveSpeed = 0.1;
document.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 87: // W
moveForward = true;
break;
case 65: // A
moveLeft = true;
break;
case 83: // S
moveBackward = true;
break;
case 68: // D
moveRight = true;
break;
}
}, false);
document.addEventListener('keyup', function(event) {
switch (event.keyCode) {
case 87: // W
moveForward = false;
break;
case 65: // A
moveLeft = false;
break;
case 83: // S
moveBackward = false;
break;
case 68: // D
moveRight = false;
break;
}
}, false);
// 渲染场景
function render() {
requestAnimationFrame(render);
// 根据用户的输入控制相机的移动
if (moveForward) {
camera.position.add(camera.getWorldDirection().multiplyScalar(moveSpeed));
}
if (moveBackward) {
camera.position.sub(camera.getWorldDirection().multiplyScalar(moveSpeed));
}
if (moveLeft) {
camera.position.sub(new THREE.Vector3().crossVectors(camera.up, camera.getWorldDirection()).normalize().multiplyScalar(moveSpeed));
}
if (moveRight) {
camera.position.add(new THREE.Vector3().crossVectors(camera.up, camera.getWorldDirection()).normalize().multiplyScalar(moveSpeed));
}
// 更新相机的方向
camera.lookAt(cube.position);
renderer.render(scene, camera);
}
render();
```
这个示例中,我们创建了一个包含地面、立方体和光源的Three.js场景。然后,我们设置相机的初始位置和方向,并且监听用户的键盘输入事件,在每一帧渲染时根据用户的输入控制相机的移动和方向。最终,我们使用`renderer.render`方法将场景渲染到屏幕上。
阅读全文