[3JS] Animations

Chenยท2024๋…„ 6์›” 16์ผ

Three.js

๋ชฉ๋ก ๋ณด๊ธฐ
4/4
post-thumbnail

requestAnimationFrame

RAF๋Š” ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ์œ„ํ•œ ๊ธฐ๋Šฅ์ด ์•„๋‹˜
๋‹ค์Œ ํ•จ์ˆ˜ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ (in a recursive manner)
์žฌ๊ท€์žฌ๊ท€์žฌ๊ท€

// Animations
function tick() {
    // Update Objects
    mesh.rotation.y += 0.01;

    // Renderer
    renderer.render(scene, camera);

    requestAnimationFrame(tick);
}

tick();

๋ฌธ์ œ์  : ์œ ์ €๋งˆ๋‹ค FPS ๋‹ค๋ฆ„..

RAF๋Š” ์ตœ๋Œ€ 60๋ฒˆ์„ ๋ชฉํ‘œ๋กœ ํ•˜๋Š”๋ฐ, ์œ ์ € ์ปด ์„ฑ๋Šฅ์— ๋”ฐ๋ผ FPS๊ฐ€ ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ. ์†”๋ฃจ์…˜์€ ์•„๋ž˜์™€ ๊ฐ™์Œ

๋ฐฉ๋ฒ• 1. JS์˜ Date.now()์„ ๊ธฐ์ค€์œผ๋กœ

cf) since 1970 Jan 1st

์™œ ์“ฐ๋‚˜?
the cube will rotate at the same speed regardless of FPS!! ์™œ๋ƒ๋ฉด ์‹œ๊ฐ„์ด ๊ธฐ์ค€์ด๋ผ์„œ ์œ ์ € ์ปดํ“จํ„ฐ ์„ฑ๋Šฅ์ด๋ž‘ ๋…ธ์ƒ๊ด€

// Time
let time = Date.now();

// Animations
function tick() {
   // Time
   const currentTime = Date.now();
   const deltaTime = currentTime - time;
   time = currentTime;

   console.log(deltaTime);
   // Update Objects
   mesh.rotation.y += 0.001 * deltaTime;

   // Renderer
   renderer.render(scene, camera);

   requestAnimationFrame(tick);
}

tick();

๋ฐฉ๋ฒ• 2. 3JS์˜ Clock

// Clock
const clock = new THREE.Clock();

getElapsedTime()

  • ๋ฐ€๋ฆฌsec๊ฐ€ ์•„๋‹ˆ๋ผ sec
  • 0 ๋ถ€ํ„ฐ ์‹œ์ž‘
    1 rotation per sec ์›ํ•˜๋ฉด!

function tick() {
    const elapsedTime = clock.getElapsedTime();

    // Update Objects
    mesh.rotation.y = elapsedTime * Math.PI * 2;
}

์ „์ฒด ์ฝ”๋“œ (mesh ์‚ฌ์ธ ์ฝ”์‹ธ์ธ)

// Animations
function tick() {
    const elapsedTime = clock.getElapsedTime();

    // Update Objects
    mesh.position.y = Math.sin(elapsedTime);
    mesh.position.x = Math.cos(elapsedTime);

์‚ฌ์ธ๋งŒ

์‚ฌ์ธ ์ฝ”์‚ฌ์ธ ๋‹ค ์คฌ์„ ๋•Œ

์ „์ฒด ์ฝ”๋“œ (์นด๋ฉ”๋ผ ์‹œ์ )

// Clock
const clock = new THREE.Clock();

// Animations
function tick() {
    const elapsedTime = clock.getElapsedTime();

    // Update Objects
    camera.position.y = Math.sin(elapsedTime);
    camera.position.x = Math.cos(elapsedTime);
    camera.lookAt(mesh.position);

    // Renderer
    renderer.render(scene, camera);

    requestAnimationFrame(tick);
}

tick();
profile
ํ˜„์‹ค์ ์ธ ๋ชฝ์ƒ๊ฐ€

0๊ฐœ์˜ ๋Œ“๊ธ€