wam 2024. 8. 28. 19:52

 

rotation

// Three.js 필수 구성 요소 초기화
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(); // 기본 1x1x1 크기의 박스
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // 초록색 기본 재질
const cube = new THREE.Mesh(geometry, material);

// 회전 순서 변경
cube.rotation.reorder("YXZ");

// 초기 회전 설정 (라디안 단위)
cube.rotation.x = Math.PI / 4; // 45도 (x축 기준)
cube.rotation.y = Math.PI / 4; // 45도 (y축 기준)

// 큐브를 씬에 추가
scene.add(cube);

// 카메라 위치 설정
camera.position.z = 5;

// 렌더링 루프
function animate() {
    requestAnimationFrame(animate);

    // 큐브 회전 (애니메이션 효과)
    cube.rotation.x += 0.01; // x축 기준으로 매 프레임마다 조금씩 회전
    cube.rotation.y += 0.01; // y축 기준으로 매 프레임마다 조금씩 회전

    renderer.render(scene, camera);
}
animate();

 

 

속성값으로 변경해 주기

 

바로 number 값으로 주면 안 된다.

mesh.rotation.y = 45;
  • 이렇게 값을 바로 주면 안 된다.
  • 변화는 생기지만 45도 회전을 준 것이 아니다.
  • 라디안에서 3.14 즉 파이가 180도이다. 2파이는 360도이다.

 

 

three.js에 내장된 MathUtils를 사용하자

mesh.rotation.y = THREE.MathUtils.degToRad(45);

 

 

파이 값으로 계산하기

mesh.rotation.x = Math.PI / 4;

파이가 180도니깐 4로 나누면 45도가 된다.

 

 

회전 순서란?

Three.js에서 객체를 회전할 때, 회전은 특정한 순서로 각 축(x, y, z)에 대해 적용된다.

기본 회전 순서는 "XYZ"이다. 이는 먼저 x축을 기준으로 회전하고, 그다음 y축, 마지막으로 z축을 기준으로 회전하는 것을 의미한다.

 

 

회전할 때 주의할 점

  mesh.rotation.y = THREE.MathUtils.degToRad(45);
  mesh.rotation.x = THREE.MathUtils.degToRad(20);
  
  function draw() {
    renderer.render(scene, camera);
    renderer.setAnimationLoop(draw);
  }
  • draw 함수 바깥에 정의했을 때 주의해야 한다.
  • 회전축이 고정되어 있기 때문에 원하는 각도대로 나오지 않을 수 있다. 회전 순서를 정의해 주자

 

 

회전 순서 정의 해주기

회전축을 독립시켜서 변경하기

  mesh.rotation.reorder("YXZ");
  mesh.rotation.y = THREE.MathUtils.degToRad(45);
  mesh.rotation.x = THREE.MathUtils.degToRad(20);
  
  function draw() {
    renderer.render(scene, camera);
    renderer.setAnimationLoop(draw);
  }
  • mesh.rotation.reorder("YXZ")의 의미
    1. 먼저 y축을 기준으로 회전
    2. 그다음 x축을 기준으로 회전
    3. 마지막으로 z축을 기준으로 회전