Three.js 多个模型沿同一轨迹运动 - 使用 THREE.Group 实现动画
要让 Three.js 中的多个模型(Mesh)沿着同一轨迹一起运动,您可以使用 'THREE.Group' 来组合这些模型,并使用动画循环函数更新它们的位置。下面是一个简单的示例:
-
导入所需的依赖:
import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; -
创建场景、相机和渲染器:
const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); -
添加控制器:
const controls = new OrbitControls(camera, renderer.domElement); -
创建一个 'THREE.Group' 用于容纳多个模型:
const group = new THREE.Group(); scene.add(group); -
创建多个模型,并将它们添加到 'group' 中:
const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const mesh1 = new THREE.Mesh(geometry, material); mesh1.position.x = -2; group.add(mesh1); const mesh2 = new THREE.Mesh(geometry, material); mesh2.position.x = 0; group.add(mesh2); const mesh3 = new THREE.Mesh(geometry, material); mesh3.position.x = 2; group.add(mesh3); -
创建动画循环函数,更新 'group' 的位置以实现模型一起运动:
function animate() { requestAnimationFrame(animate); group.rotation.y += 0.01; // 可选的旋转动画 group.position.y = Math.sin(Date.now() * 0.001); // 沿y轴移动的动画 renderer.render(scene, camera); } animate();
在上述代码中,我们创建了一个 'THREE.Group' 并将多个模型(Mesh)添加到其中。然后,我们在动画循环函数中更新该 'group' 的位置,实现多个模型沿着同一轨迹一起运动。您可以根据需要调整旋转、移动和动画效果。
原文地址: https://www.cveoy.top/t/topic/lMX 著作权归作者所有。请勿转载和采集!