three.js中的动画有哪些类型?如何创建动画?

85 阅读2分钟

three.js中的动画有哪些类型?如何创建动画?

Three.js中的动画类型有基于时间的动画(如动画曲线和时间轴),基于物理的动画(如刚体动力学和碰撞检测),以及基于着色器的动画(如顶点着色器和片元着色器)。可以通过Three.js提供的AnimationMixer和AnimationAction来创建动画。首先需要创建一个AnimationAction对象,然后将其与物体关联起来,最后通过AnimationMixer来控制动画的播放和时间轴的推进等。

在Three.js中,创建动画主要有两种方式:使用内置的动画函数,或者使用动画控制器。这些都可以用来创建复杂的动画序列。

  1. 使用内置的动画函数

Three.js提供了内置的动画函数,如requestAnimationFrame()Clock对象。requestAnimationFrame()函数用于在下一次重绘之前执行特定的函数,Clock对象可以用来跟踪经过的时间。

以下是一个使用requestAnimationFrame()的简单例子:

let animation = function() {  
  let clock = new THREE.Clock();  
  let geometry = new THREE.BoxGeometry(1, 1, 1);  
  let material = new THREE.MeshBasicMaterial({color: 0x00ff00});  
  let cube = new THREE.Mesh(geometry, material);  
  let scene = new THREE.Scene();  
  scene.add(cube);  
  let camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);  
  camera.position.z = 2;  
  camera.position.y = 1;  
  camera.lookAt(cube.position);  
  let renderer = new THREE.WebGLRenderer();  
  renderer.setSize(window.innerWidth, window.innerHeight);  
  document.body.appendChild(renderer.domElement);  
  let animate = function() {  
    requestAnimationFrame(animate);  
    let delta = clock.getDelta(); // delta is the amount of time elapsed since the last call to requestAnimationFrame()  
    cube.rotation.x += delta; // rotate the cube based on the amount of time elapsed  
    cube.rotation.y += delta; // rotate the cube based on the amount of time elapsed  
    renderer.render(scene, camera); // render the scene  
  };  
  animate(); // start the animation loop  
};  
animation(); // call the animation function to start the animation loop
  1. 使用动画控制器

Three.js提供了各种动画控制器,如AnimationMixerAnimationAction,用于控制复杂的动画序列。这些控制器可以控制物体的旋转、缩放、位置等属性。以下是一个使用AnimationMixerAnimationAction的例子:

let mixer, animationAction;  
let mixer = new THREE.AnimationMixer(cube); // create an AnimationMixer to control the animation of the cube object  
let animationAction = mixer.clipAction(animationClip); // create an AnimationAction using the clip and mixer  
animationAction.play(); // play the animation action