ThreeJS - Snippets

Aus Wikizone
Wechseln zu: Navigation, Suche

Animation Basics

Die Beispiele setzen eine Setup mit einem Camera Object 'camera', einer Szene scene, und einem Renderer 'renderer' voraus.

Pure JavaScript calculation

let time = Date.now() 
const tick = () =>
{
    // JS based time calculation
    const currentTime = Date.now()
    const deltaTime = currentTime - time
    time = currentTime
    //console.log(deltaTime)
    // Update objects
    mesh.rotation.y += 0.001 * deltaTime
    renderer.render(scene, camera)
    // tell JS to call tick on the next frame
    window.requestAnimationFrame(tick)

ThreeJS Clock

const clock = new THREE.Clock()
const tick = () =>
{
    // Hint: do NOT use clock.getDelta() - it can cause problems (buggy in end of 2021)
    const elapsedTime = clock.getElapsedTime()
    //console.log(elapsedTime)
    mesh.rotation.y = elapsedTime * Math.PI * 2 // one revolution / s
    camera.lookAt(mesh.position)
    camera.position.z = Math.sin(elapsedTime) // back and forth
    // Render
    renderer.render(scene, camera)
    window.requestAnimationFrame(tick) 
}
tick()

GSAP Animation