【Three.js】手把手教你在三维场景中实现人物行走动画效果
    		       		warning:
    		            这篇文章距离上次修改已过452天,其中的内容可能已经有所变动。
    		        
        		                
                
// 引入必要的Three.js组件
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
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 loader = new GLTFLoader();
loader.load('models/gltf/RobotExpressive.gltf', function (gltf) {
  scene.add(gltf.scene);
  // 设置动画循环
  gltf.animations; // 获取动画数组
  gltf.scene.rotation.y = Math.PI; // 确保人物面朝右方
  mixer = new THREE.AnimationMixer(gltf.scene);
  for (let i = 0; i < gltf.animations.length; i++) {
    const clip = gltf.animations[i];
    const action = mixer.clipAction(clip);
    action.weight = 1;
    action.play();
  }
  // 播放idle动画
  const clip = THREE.AnimationClip.findByName(gltf.animations, 'Idle');
  const idleAction = mixer.clipAction(clip);
  idleAction.loop = THREE.LoopOnce;
  idleAction.clampWhenFinished = true;
  idleAction.play();
}, undefined, function (error) {
  console.error(error);
});
 
// 设置OrbitControls,允许用户通过鼠标和触摸旋转视图
const controls = new OrbitControls(camera, renderer.domElement);
 
// 设置渲染循环
function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
  if (mixer) mixer.update(clock.getDelta()); // 更新动画
}
 
// 启动渲染循环
const clock = new THREE.Clock();
animate();这段代码展示了如何在Three.js中加载一个带有动画的3D人物模型,并在加载完成后设置动画循环。代码使用了GLTFLoader来加载glTF格式的模型,并通过AnimationMixer来控制动画的播放。OrbitControls允许用户通过鼠标或触摸旋转查看场景。最后,代码中的animate函数是渲染循环的主要部分,它会不断调用自身以更新场景和播放动画。
评论已关闭