티스토리 뷰

code/three.js

06. Animations

golee922 2021. 7. 2. 10:06

framerate를 사용하는 방법


/**
 * Animate
 */
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()

결과 : 큐브는 왼쪽으로 천천히 돌아감

사용자 컴퓨터 성능에 따라 framerate 가 다르기때문에, 그걸 맞춰주기 위해 움직임 값에 deltaTime (1frame당 걸리는 시간) 을 곱해주어
모든 컴퓨터에서 똑같이 보일 수 있도록 함

 

 

 

 

Clock 사용하기


/**
 * Animate
 */
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

    // Update objects
    mesh.rotation.y = elapsedTime

    // ...
}

tick()

clock.getElapsedTime()Clock 객체가 생성된 이후 시간이 얼마나 흘렀는지를 리턴한다.

/**
 * Animate
 */
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

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

    // ...
}

tick()

위 코드의 결과로 물체는 동그랗게 원을 그리며 움직인다.

/**
 * Animate
 */
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

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

    // ...
}

tick()

Object3D를 상속하는 모든 객체 (e.g. camera) 에 사용할 수 있음

 

 

외부 라이브러리 사용하기 (GSAP)


npm install -save gsap

import './style.css'
import * as THREE from 'three'
import gsap from 'gsap'

/**
 * Animate
 */
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()

1초 후 (delay) 1초 동안 (duration) 2만큼 x방향으로 (x) 움직임

'code > three.js' 카테고리의 다른 글

05. Transform objects  (0) 2021.06.27
03. Basic scene  (0) 2021.06.27
What is WebGL?  (0) 2021.06.27
Three.js journey 시작!  (0) 2021.06.26