THREE.AnimationMixer
是 Three.js 库中用于处理动画的一个类。它允许你管理多个动画剪辑(THREE.AnimationAction
)在单个或多个对象上的播放。以下是对 new THREE.AnimationMixer()
的入参、方法和属性的简要讲解:
入参
new THREE.AnimationMixer(root)
root
(必需):一个THREE.Object3D
类型的对象,它是你想要应用动画的根对象。通常,这是一个场景(THREE.Scene
)中的网格(THREE.Mesh
)或其他对象。
方法
-
clipAction(clip[, root])
clip
(必需):一个THREE.AnimationClip
对象,它包含你想要播放的动画数据。root
(可选):与AnimationMixer
构造函数的root
参数相同。如果你在这里指定了root
,那么它将覆盖AnimationMixer
的root
设置,并仅对该对象应用此动画。- 返回一个
THREE.AnimationAction
对象,你可以使用它来播放、暂停、停止等控制动画。
-
timeScale
- 这是一个 getter/setter 方法,用于获取或设置动画的播放速度。例如,
mixer.timeScale = 2;
将使所有动画播放速度加倍。
- 这是一个 getter/setter 方法,用于获取或设置动画的播放速度。例如,
-
uncacheClip(clip)
- 从混合器的缓存中删除指定的动画剪辑。通常,在不再需要某个动画时调用此方法以释放内存。
-
uncacheAll()
- 从混合器的缓存中删除所有动画剪辑。
属性
-
time
- 一个只读属性,表示从动画开始到现在的总时间(以秒为单位)。
-
runningActions
- 一个只读属性,返回一个包含当前正在运行的
THREE.AnimationAction
对象的数组。
- 一个只读属性,返回一个包含当前正在运行的
使用示例
// 假设你有一个 THREE.Mesh 对象名为 mesh
var mixer = new THREE.AnimationMixer(mesh);
// 假设你有一个 THREE.AnimationClip 对象名为 clip
var action = mixer.clipAction(clip);
// 开始播放动画
action.play();
// 在动画更新循环中
function animate() {
requestAnimationFrame(animate);
var delta = clock.getDelta(); // 假设你有一个 THREE.Clock 对象名为 clock
mixer.update(delta); // 更新所有动画
// ... 其他渲染代码 ...
}
animate();
<!DOCTYPE html> <!-- 声明文档类型为HTML5 -->
<html lang="en"> <!-- 指定页面语言为英语 -->
<head>
<title>three.js webgl - animation - skinning</title> <!-- 设置页面标题 -->
<meta charset="utf-8"> <!-- 指定字符编码 -->
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <!-- 设置视口相关属性 -->
<link type="text/css" rel="stylesheet" href="main.css"> <!-- 引入CSS样式表 -->
<style>
a {
color: #f00; <!-- 设置链接颜色为红色 -->
}
</style>
</head>
<body>
<div id="container"></div> <!-- 创建一个用于渲染的容器 -->
<div id="info">
<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Skeletal Animation Blending <!-- 显示链接文本 -->
(model from <a href="https://www.mixamo.com/" target="_blank" rel="noopener">mixamo.com</a>)<br/> <!-- 显示链接文本 -->
Note: crossfades are possible with blend weights being set to (1,0,0), (0,1,0) or (0,0,1) <!-- 显示注释 -->
</div>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js", <!-- 导入three.js库 -->
"three/addons/": "./jsm/" <!-- 导入附加模块 -->
}
}
</script>
<script type="module"> <!-- 使用ES6模块化语法 -->
import * as THREE from 'three'; <!-- 导入three.js库的全部内容 -->
import Stats from 'three/addons/libs/stats.module.js'; <!-- 导入性能统计模块 -->
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'; <!-- 导入GUI模块 -->
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; <!-- 导入GLTFLoader模块 -->
let scene, renderer, camera, stats; <!-- 定义变量 -->
let model, skeleton, mixer, clock; <!-- 定义变量 -->
const crossFadeControls = []; <!-- 定义数组 -->
let idleAction, walkAction, runAction; <!-- 定义变量 -->
let idleWeight, walkWeight, runWeight; <!-- 定义变量 -->
let actions, settings; <!-- 定义变量 -->
let singleStepMode = false; <!-- 定义变量 -->
let sizeOfNextStep = 0; <!-- 定义变量 -->
init(); <!-- 调用初始化函数 -->
function init() {
const container = document.getElementById( 'container' ); <!-- 获取渲染容器 -->
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 100 ); <!-- 创建透视相机 -->
camera.position.set( 1, 2, - 3 ); <!-- 设置相机位置 -->
camera.lookAt( 0, 1, 0 ); <!-- 设置相机朝向 -->
clock = new THREE.Clock(); <!-- 创建时钟对象 -->
scene = new THREE.Scene(); <!-- 创建场景 -->
scene.background = new THREE.Color( 0xa0a0a0 ); <!-- 设置场景背景颜色 -->
scene.fog = new THREE.Fog( 0xa0a0a0, 10, 50 ); <!-- 设置场景雾效 -->
const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x8d8d8d, 3 ); <!-- 创建半球光源 -->
hemiLight.position.set( 0, 20, 0 ); <!-- 设置光源位置 -->
scene.add( hemiLight ); <!-- 将光源添加到场景中 -->
const dirLight = new THREE.DirectionalLight( 0xffffff, 3 ); <!-- 创建平行光源 -->
dirLight.position.set( - 3, 10, - 10 ); <!-- 设置光源位置 -->
dirLight.castShadow = true; <!-- 开启阴影 -->
dirLight.shadow.camera.top = 2; <!-- 设置阴影摄像机参数 -->
dirLight.shadow.camera.bottom = - 2;
dirLight.shadow.camera.left = - 2;
dirLight.shadow.camera.right = 2;
dirLight.shadow.camera.near = 0.1;
dirLight.shadow.camera.far = 40;
scene.add( dirLight ); <!-- 将光源添加到场景中 -->
// scene.add( new THREE.CameraHelper( dirLight.shadow.camera ) ); <!-- 添加相机辅助线 -->
// ground
const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0xcbcbcb, depthWrite: false } ) ); <!-- 创建地面 -->
mesh.rotation.x = - Math.PI / 2; <!-- 设置地面旋转 -->
mesh.receiveShadow = true; <!-- 接收阴影 -->
scene.add( mesh ); <!-- 将地面添加到场景中 -->
const loader = new GLTFLoader(); <!-- 创建GLTF加载器 -->
loader.load( 'models/gltf/Soldier.glb', function ( gltf ) { <!-- 加载模型 -->
model = gltf.scene; <!-- 获取模型对象 -->
scene.add( model ); <!-- 将模型添加到场景中 -->
model.traverse( function ( object ) { <!-- 遍历模型中的所有对象 -->
if ( object.isMesh ) object.castShadow = true; <!-- 设置网格对象投射阴影 -->
} );
//
skeleton = new THREE.SkeletonHelper( model ); <!-- 创建骨骼辅助对象 -->
skeleton.visible = false; <!-- 设置骨骼辅助对象不可见 -->
scene.add( skeleton ); <!-- 将骨骼辅助对象添加到场景中 -->
//
createPanel(); <!-- 调用创建面板函数 -->
//
const animations = gltf.animations; <!-- 获取模型动画数组 -->
mixer = new THREE.AnimationMixer( model ); <!-- 创建动画混合器对象 -->
idleAction = mixer.clipAction( animations[ 0 ] ); <!-- 创建动作对象 -->
walkAction = mixer.clipAction( animations[ 3 ] );
runAction = mixer.clipAction( animations
[ 1 ] );
actions = [ idleAction, walkAction, runAction ]; <!-- 将动作对象存入数组中 -->
activateAllActions(); <!-- 激活所有动作对象 -->
animate(); <!-- 调用动画函数 -->
} );
renderer = new THREE.WebGLRenderer( { antialias: true } ); <!-- 创建WebGL渲染器 -->
renderer.setPixelRatio( window.devicePixelRatio ); <!-- 设置像素比例 -->
renderer.setSize( window.innerWidth, window.innerHeight ); <!-- 设置渲染器尺寸 -->
renderer.shadowMap.enabled = true; <!-- 开启阴影映射 -->
container.appendChild( renderer.domElement ); <!-- 将渲染器元素添加到容器中 -->
stats = new Stats(); <!-- 创建性能统计对象 -->
container.appendChild( stats.dom ); <!-- 将性能统计元素添加到容器中 -->
window.addEventListener( 'resize', onWindowResize ); <!-- 监听窗口大小变化事件 -->
}
function createPanel() { <!-- 创建面板函数开始 -->
const panel = new GUI( { width: 310 } ); <!-- 创建GUI面板对象 -->
const folder1 = panel.addFolder( 'Visibility' ); <!-- 创建GUI折叠菜单对象 -->
const folder2 = panel.addFolder( 'Activation/Deactivation' );
const folder3 = panel.addFolder( 'Pausing/Stepping' );
const folder4 = panel.addFolder( 'Crossfading' );
const folder5 = panel.addFolder( 'Blend Weights' );
const folder6 = panel.addFolder( 'General Speed' );
settings = { <!-- 定义设置对象 -->
'show model': true,
'show skeleton': false,
'deactivate all': deactivateAllActions,
'activate all': activateAllActions,
'pause/continue': pauseContinue,
'make single step': toSingleStepMode,
'modify step size': 0.05,
'from walk to idle': function () {
prepareCrossFade( walkAction, idleAction, 1.0 );
},
'from idle to walk': function () {
prepareCrossFade( idleAction, walkAction, 0.5 );
},
'from walk to run': function () {
prepareCrossFade( walkAction, runAction, 2.5 );
},
'from run to walk': function () {
prepareCrossFade( runAction, walkAction, 5.0 );
},
'use default duration': true,
'set custom duration': 3.5,
'modify idle weight': 0.0,
'modify walk weight': 1.0,
'modify run weight': 0.0,
'modify time scale': 1.0
};
folder1.add( settings, 'show model' ).onChange( showModel ); <!-- 添加控制面板项 -->
folder1.add( settings, 'show skeleton' ).onChange( showSkeleton );
folder2.add( settings, 'deactivate all' );
folder2.add( settings, 'activate all' );
folder3.add( settings, 'pause/continue' );
folder3.add( settings, 'make single step' );
folder3.add( settings, 'modify step size', 0.01, 0.1, 0.001 );
crossFadeControls.push( folder4.add( settings, 'from walk to idle' ) );
crossFadeControls.push( folder4.add( settings, 'from idle to walk' ) );
crossFadeControls.push( folder4.add( settings, 'from walk to run' ) );
crossFadeControls.push( folder4.add( settings, 'from run to walk' ) );
folder4.add( settings, 'use default duration' );
folder4.add( settings, 'set custom duration', 0, 10, 0.01 );
folder5.add( settings, 'modify idle weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
setWeight( idleAction, weight );
} );
folder5.add( settings, 'modify walk weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
setWeight( walkAction, weight );
} );
folder5.add( settings, 'modify run weight', 0.0, 1.0, 0.01 ).listen().onChange( function ( weight ) {
setWeight( runAction, weight );
} );
folder6.add( settings, 'modify time scale', 0.0, 1.5, 0.01 ).onChange( modifyTimeScale );
folder1.open(); <!-- 展开折叠菜单 -->
folder2.open();
folder3.open();
folder4.open();
folder5.open();
folder6.open();
}
function showModel( visibility ) { <!-- 控制模型可见性函数 -->
model.visible = visibility;
}
function showSkeleton( visibility ) { <!-- 控制骨骼可见性函数 -->
skeleton.visible = visibility;
}
function modifyTimeScale( speed ) { <!-- 修改动画播放速度函数 -->
mixer.timeScale = speed;
}
function deactivateAllActions() { <!-- 停止所有动画函数 -->
actions.forEach( function ( action ) {
action.stop();
} );
}
function activateAllActions() { <!-- 激活所有动画函数 -->
setWeight( idleAction, settings[ 'modify idle weight' ] );
setWeight( walkAction, settings[ 'modify walk weight' ] );
setWeight( runAction, settings[ 'modify run weight' ] );
actions.forEach( function ( action ) {
action.play();
} );
}
function pauseContinue() { <!-- 暂停/继续动画函数 -->
if ( singleStepMode ) {
singleStepMode = false;
unPauseAllActions();
} else {
if ( idleAction.paused ) {
unPauseAllActions();
} else {
pauseAllActions();
}
}
}
function pauseAllActions() { <!-- 暂停所有动画函数 -->
actions.forEach( function ( action ) {
action.paused = true;
} );
}
function unPauseAllActions() { <!-- 恢复所有动画函数 -->
actions.forEach( function ( action ) {
action.paused = false;
} );
}
function toSingleStepMode() { <!-- 设置为单步模式函数 -->
unPauseAllActions();
s
ingleStepMode = true;
sizeOfNextStep = settings[ 'modify step size' ];
}
function prepareCrossFade( startAction, endAction, defaultDuration ) { <!-- 准备混合动画函数 -->
// Switch default / custom crossfade duration (according to the user's choice)
const duration = setCrossFadeDuration( defaultDuration );
// Make sure that we don't go on in singleStepMode, and that all actions are unpaused
singleStepMode = false;
unPauseAllActions();
// If the current action is 'idle' (duration 4 sec), execute the crossfade immediately;
// else wait until the current action has finished its current loop
if ( startAction === idleAction ) {
executeCrossFade( startAction, endAction, duration );
} else {
synchronizeCrossFade( startAction, endAction, duration );
}
}
function setCrossFadeDuration( defaultDuration ) { <!-- 设置混合动画持续时间函数 -->
// Switch default crossfade duration <-> custom crossfade duration
if ( settings[ 'use default duration' ] ) {
return defaultDuration;
} else {
return settings[ 'set custom duration' ];
}
}
function synchronizeCrossFade( startAction, endAction, duration ) { <!-- 同步混合动画函数 -->
mixer.addEventListener( 'loop', onLoopFinished );
function onLoopFinished( event ) {
if ( event.action === startAction ) {
mixer.removeEventListener( 'loop', onLoopFinished );
executeCrossFade( startAction, endAction, duration );
}
}
}
function executeCrossFade( startAction, endAction, duration ) { <!-- 执行混合动画函数 -->
// Not only the start action, but also the end action must get a weight of 1 before fading
// (concerning the start action this is already guaranteed in this place)
setWeight( endAction, 1 );
endAction.time = 0;
// Crossfade with warping - you can also try without warping by setting the third parameter to false
startAction.crossFadeTo( endAction, duration, true );
}
// This function is needed, since animationAction.crossFadeTo() disables its start action and sets
// the start action's timeScale to ((start animation's duration) / (end animation's duration))
function setWeight( action, weight ) { <!-- 设置动画权重函数 -->
action.enabled = true;
action.setEffectiveTimeScale( 1 );
action.setEffectiveWeight( weight );
}
// Called by the render loop
function updateWeightSliders() { <!-- 更新权重滑块函数 -->
settings[ 'modify idle weight' ] = idleWeight;
settings[ 'modify walk weight' ] = walkWeight;
settings[ 'modify run weight' ] = runWeight;
}
// Called by the render loop
function updateCrossFadeControls() { <!-- 更新混合动画控制函数 -->
if ( idleWeight === 1 && walkWeight === 0 && runWeight === 0 ) {
crossFadeControls[ 0 ].disable();
crossFadeControls[ 1 ].enable();
crossFadeControls[ 2 ].disable();
crossFadeControls[ 3 ].disable();
}
if ( idleWeight === 0 && walkWeight === 1 && runWeight === 0 ) {
crossFadeControls[ 0 ].enable();
crossFadeControls[ 1 ].disable();
crossFadeControls[ 2 ].enable();
crossFadeControls[ 3 ].disable();
}
if ( idleWeight === 0 && walkWeight === 0 && runWeight === 1 ) {
crossFadeControls[ 0 ].disable();
crossFadeControls[ 1 ].disable();
crossFadeControls[ 2 ].disable();
crossFadeControls[ 3 ].enable();
}
}
function onWindowResize() { <!-- 窗口大小变化事件处理函数 -->
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() { <!-- 动画函数开始 -->
// Render loop
requestAnimationFrame( animate ); <!-- 请求下一帧动画 -->
idleWeight = idleAction.getEffectiveWeight();
walkWeight = walkAction.getEffectiveWeight();
runWeight = runAction.getEffectiveWeight();
// Update the panel values if weights are modified from "outside" (by crossfadings)
updateWeightSliders();
// Enable/disable crossfade controls according to current weight values
updateCrossFadeControls();
// Get the time elapsed since the last frame, used for mixer update (if not in single step mode)
let mixerUpdateDelta = clock.getDelta();
// If in single step mode, make one step and then do nothing (until the user clicks again)
if ( singleStepMode ) {
mixerUpdateDelta = sizeOfNextStep;
sizeOfNextStep = 0;
}
// Update the animation mixer, the stats panel, and render this frame
mixer.update( mixerUpdateDelta );
stats.update();
renderer.render( scene, camera );
}
</script>
</body>
</html>