Three.js - 간단한 Animation을 넣어보자

 

 

requestAnimationFrame 함수

Animation 효과를 주기 위해 setInterval 함수를 쓸 수 있지만,

setInterval는 브라우저의 다른 탭을 사용할 때도 계속 호출되기 때문에 CPU를 많이 사용한다.

이를 보안하기 위하여 내장 함수인 requestAnimationFrame를 사용한다.

자세한 건 microsoft에서 나온 requestAnimationFrame 의 설명을 한번 보자!

 

 

requestAnimationFrame 시작!

plane과 scene, 그리고 cube까지 만들어놓는다.

기존 소스에서 animation이라는 함수를 추가하여 Animation 효과를 줄 수 있다.

<script type="text/javascript">
	function animation() {          
        cube.rotation.x += 0.02;
        cube.rotation.y += 0.02;
        cube.rotation.z += 0.02;  
        requestAnimationFrame(animation);        
        renderer.render(scene, camera);
    }    
    animation();
</script>

 

animation이 호출될 때마다 cube의 x축, y축, z축에 rotation속성이 0.02씩 증가를 시킨다.

함수 안에서 Animation이 무한 반복되도록 requestAnimationFrame함수에 animation인자를 넣어 호출한다.

이전에선 전체 장면 생성 후 renderer.render를 호출하였는데, Animation을 시작하기 위해서 animation함수를 호출한다.

 

See the Pen three.js animation by 최충현 (@nenara) on CodePen.

 

오호 cube가 움직인다.

 

 

다른 도형도 넣어서 다른 모션을 주어보자!

나는 20면체를 만들 건데 cube를 만들었던 방식과 동일하다.

도형을 새로운 변수에 담아 scene에 추가!!

<script type="text/javascript">
	var icosahedronGeometry = new THREE.IcosahedronGeometry(4, 4, 4);
	var icosahedronMaterial = new THREE.MeshLambertMaterial({color: 0x12db00, wireframe: false});
	var icosahedron = new THREE.Mesh(icosahedronGeometry, icosahedronMaterial);
	icosahedron.castShadow = true;
	icosahedron.position.x = -4;
	icosahedron.position.y = 5;
	icosahedron.position.z = 0;
	scene.add(icosahedron);  
</script>

 

icosahedronGeometry에서 THREE.IcosahedronGeometry로 변경을 해준다.

three.js안에 여러 도형(ex - CircleGeometry)이 내장되어 있으니 원하는 도형은 찾아서 사용해본다!

<script type="text/javascript">
	var step = 0;
	animation();
	function animation() {           
		step += 0.01;
		icosahedron.position.y = 3 + ( 5 * Math.abs(Math.sin(step)));
		requestAnimationFrame(animation);
		renderer.render(scene, camera);
	}
</script>

step이라는 변수를 추가해준다 (속도조절을 위한)

step은 animation함수가 실행될 때마다 0.01씩 증가한다.

위아래로 뛸 거니 position y값을 만지면 된다.

 

See the Pen three.js - 20면체 by 최충현 (@nenara) on CodePen.

오호 20면체가 움직인다.

 

 

위의 Animation을 응용하여!!!

<script type="text/javascript">
	animation();
	function animation() {           
		step += 0.01;
		sphere.position.x = 20 + ( 10 * (Math.cos(step)));
		sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step)));
		sphere.rotation.x += 0.02;
		sphere.rotation.y += 0.02;
		sphere.rotation.z += 0.02;
		requestAnimationFrame(animation);
		renderer.render(scene, camera);
	}
</script>

position x축 cos, y축 sin 이동, rotation x축, y축, z축 뒹굴뒹굴~~

 

See the Pen WNbqZLM by 최충현 (@nenara) on CodePen.

앞뒤로 위아래 뒹굴뒹굴 돌면서 완성!! 완성완성!! 완성!!

 

 

 



출처: https://jj-k-ul.tistory.com/entry/Threejs-간단한-Animation를-넣어보자?category=1046305 [불꽃놀이보고싶다]

 

+ Recent posts