帧速率:屏幕以特定的频率运行。帧速率主要取决于屏幕,但计算机本身也有限制。大多数屏幕以每秒60帧的速度运行。这意味着大约每16毫秒一帧。但有些屏幕可以运行得快得多,当计算机处理东西遇到困难时,它会运行得更慢。
一、requestAnimationFrame
函数内部添加renderer.render(…)调用
const tick = () =>
{
// Update objects
mesh.rotation.y += 0.01
// Render
renderer.render(scene, camera)
// Call tick again on the next frame
window.requestAnimationFrame(tick)
}
tick()
在具有高帧率的计算机上,立方体将旋转得更快,而如果在较低的帧率上测试,立方体将旋转得更慢
适应帧速率
基于自上一帧以来花费的时间来旋转,无论帧速率如何,这个旋转速度在每个屏幕和每个计算机上都将是相同的。
let time = Date.now()
const tick = () =>
{
// Time
const currentTime = Date.now()
const deltaTime = currentTime - time
time = currentTime
// Update objects
mesh.rotation.y += 0.01 * deltaTime
// ...
}
tick()
二、Clock 处理时间计算
- getElapsedTime 自时钟创建以来已经过去了多少秒
const clock = new THREE.Clock()
const elapsedTime = clock.getElapsedTime()
- getDelta
除非你确切知道Clock类代码中发生了什么,否则不应该使用它。使用它可能会扰乱你的动画,你会得到不想要的结果
三、动画库 gsap
gsap.to(mesh.position, { duration: 1, delay: 1, x: 2 })
const tick = () =>
{
// Render
renderer.render(scene, camera)
// Call tick again on the next frame
window.requestAnimationFrame(tick)
}
tick()
GSAP有一个内置的requestAnimationFrame,所以你不需要自己更新动画,但是,如果你想看到立方体移动,你仍然需要在每一帧上继续渲染你的场景。