ThreeJS - Snippets

Aus Wikizone
Wechseln zu: Navigation, Suche

Links

ThreeJS

Animation Basics

Timebased Tick / Loop Function

Für Animationen können wir in einem Loop die Szene Rendern, Objekte verändern, Szene erneut Rendern usw. In JavaScript kann man dazu die window.requestAnimationFrame Funktion nutzen. Damit die zeitlichen Abläufe nicht von der Rechnerleistung sondern rein von der Zeit abhängen gibt es einige Möglichkeiten diesen Loop umzusetzen.

Die Beispiele setzen eine Setup mit einem Camera Object 'camera', einer Szene scene, und einem Renderer 'renderer' voraus. Du kannst z.B. das Beispiel auf der Hauptseite nutzen.

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) 
}
// go...
tick()

ThreeJS Clock Object

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()

Nützliche Snippets für Animationen

Kreisbewegung / Circular Movement

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

Cursor auswerten

// Sizes
const sizes = { width: 800,  height: 600}
// Cursor
const cursor = {
    x: 0,
    y: 0
}
window.addEventListener('mousemove', (event) => 
{
    //cursor.x = event.clientX / sizes.width // 0 <= x <= 1
    cursor.x = event.clientX / sizes.width - 0.5// -0.5 <= x <= +0.5
    cursor.y = event.clientY / sizes.height - 0.5// -0.5 <= x <= +0.5
    console.log('x: ' + cursor.x)
    console.log('y: ' + cursor.y)
})