1. three.js 기초 를 따라했다면 빈 캔버스에 움직이지 않는 물체를 그릴 수 있게 되었을 것이다.
다음으로 할 일은 그 물체를 움직이는 것이다
애니메이션에는 2가지 방법이 있는데, 첫 번째로는 내부함수 requestAnimateFrame 을 사용하는 것이다.
매 프레임마다 캔버스를 다시 render 해주고 그 때 requestAnimateFrame 함수를 사용해주면 부드러운 애니메이션을 사용할 수 있다.
다른 방법으로는 renderer.setAnimationLoop 이다. 두 방법에서 크게 다른 점은 없으나 VR을 만들 때는 이 방법을 써야 한다고 공식 문서에 적혀있다
import * as THREE from "three";
const example = () => {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
//둘중 아무거나 선택
//requestAnimationFrame(animate);
//renderer.setAnimationLoop(animate);
}
animate();
};
export default example;
이렇게 애니메이션을 적용했을 때, 성능이 좋은 컴퓨터에서는 1초에 100번 animate 함수가 실행되고, 어떤 컴퓨터에서는 10번만 실행될 수 있다.
그런 문제를 해결하기 위해서 three.js 는 clock 를 사용하도록 권장하고 있다. 위의 코드에서 animate 함수가 실행될 때 마다 rotation을 0.1 씩 더하고 있다.
clock.getDelta 함수는 animate 가 실행 될 때 이전 실행 되었던 시간과의 차이 값을 리턴 한다. 이를 이용해서 모든 컴퓨터에서 동일한 속도로 애니메이션이 실행 되도록 할 수 있다.
const clock=new THREE.Clock()
function animate(){
const delta=clock.getDelta();
cube.rotation.x += delta;
cube.rotation.y += delta;
renderer.render(scene,camera);
renderer.setAnimationLoop(animate);
}