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.

Kreisbewegung / Circular Movement

myObject.position.y = Math.sin(elapsedTime) //(-1 -> 1 -> -1 -> ...)
myObject.position.x = Math.cos(elapsedTime)

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

// GSAP has it's own requestAnimationFrame, thus no time calculation needed
// we just let gsap update our values and tick does render each frame
gsap.to(mesh.position,{ duration: 1, delay: 1, x: 2 })
gsap.to(mesh.position,{ duration: 1, delay: 1, x: 0 })

const tick = () =>
{
    // Render on each frame
    renderer.render(scene, camera)
    window.requestAnimationFrame(tick) 
}

// GO...
tick()