使用 Three.js 搭建元宇宙基础交互 | 大帅老猿 Three.js 特训
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// 设置场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 添加灯光
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 0.5).normalize();
scene.add(directionalLight);
// 创建地形和材质
const geometry = new THREE.PlaneGeometry(100, 100, 100, 100);
const material = new THREE.MeshPhongMaterial({ color: 0xffffff, depthWrite: false });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// 添加模型
const gltfLoader = new THREE.GLTFLoader();
gltfLoader.load('models/scene.gltf', (gltf) => {
scene.add(gltf.scene);
});
// 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
这段代码示例展示了如何使用Three.js创建一个基本的3D场景,并加载一个模型和轨道控制器,以便用户可以以第一人称视角探索虚拟环境。代码简洁,注重核心功能的实现,并提供了一个清晰的学习路径。
评论已关闭