基础动画

更新时间: 2021-04-26 09:15:12
  • 基础动画Threejs里所有动画的基础,修改对象的三个属性:位置、旋转和缩放。
  • 移动相机: 动画中一个很重要的部分是在场景中移动相机的能力。
  • 变形和蒙皮: 制作复杂模型的动画主要有两种方式。使用变形技术,定义几何体之间的过渡;以及使用骨骼和蒙皮技术处理这种过渡。
  • 加载外部动画

# 基础动画

在看例子之前,我们先快速回顾一下render(渲染)循环。为了支持动画,我们需要告诉Three.js多久渲染一次场景。为此,我们要使用由HTML5提供的标准的requestAnimationFrame函数:

render();

function render(){
  //render the scene
  render.render(scene,camera);

  //schedule the next rendering using requestAnimationFrame
  requestAnimationFrame(render);
}
1
2
3
4
5
6
7
8
9

这段代码里,我们只需要在初始化场景时调用一次render()函数。在render()函数中,我们用requestAnimationFrame来安排下一次渲染。这样,浏览器就可以保证以正确的时间间隔(通常是60次每秒)调用render()函数。通过requestAnimationFrame,我们不必告诉浏览器什么时候需要刷新屏幕,而是请求浏览器在最适合的时候执行我们提供的函数。通常情况下其结果是60fps(帧频)。使用requestAnimationFrame会让你的动画运行得更加平缓,而且对CPU和GPU更加友好,你再也不必再担心渲染时机的问题。

# 简单动画

我们通过改变对象的旋转、缩放、位置、材质、顶点、面,以及其他你想得到的东西,可以很容易地制作出动画。在下一次的render循环中,Threejs就可以渲染这些修改后的属性。

该示例的render循环非常简单。你只要修改网格的属性即可,Threejs会处理剩下的事情:

function render(){
  stats.update();
  trackballControls.update(clock.getDelta())

  cube.rotation.x += controls.rotationSpeed
  cube.rotation.y += controls.rotationSpeed
  cube.rotation.z += controls.rotationSpeed

  step += controls.bouncingSpeed
  sphere.position.x = 20 + (10 * (Math.cos(step)))
  sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)))

  scalingStep += controls.scalingSpeed
  var scaleX = Math.abs(Math.sin(scalingStep / 4))
  var scaleY = Math.abs(Math.cos(scalingStep / 5))
  var scaleZ = Math.abs(Math.sin(scalingStep / 7))

  cylinder.scale.set(scaleX,scaleY,scaleZ)

  requestAnimationFrame(renderScene)
  renderer.render(scene, camera)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

注意

本博客的dat.gui.js 和 stats.js都是改造过的
stats.js 加上了domEl参数,让stats可以添加到某个确定的dom中去
dat.gui.js改动稍微多一点,
首先第2338行的 GUI 方法,加上了domEl参数,同上
然后第2611行的appendChild使用了domEl,将gui面板添加到domEl中去
然后在gui被销毁掉之后将 autoPlaceVirgin 这个全局变量置为 true,修复下一次点进页面不能添加gui的问题