Web Frontend Developer

[Three.js] Transform Objects

DevOwen 2022. 10. 17. 10:00

4 properties to transform objects

  1. position
  2. scale
  3. rotation
  4. quaternion

Object3D를 상속받는 모든 클래스들은 위의 4가지 속성을 가진다. 예컨데, 여기에는 PerspectiveCameraMesh가 있다.

이러한 속성들은 행렬(matrix)으로 컴파일 된다.

position objects

position 속성은 다음과 같이 3차원에서 x,y,z 축을 의미

사용하는 단위 1은 단위로 인식하면 되고, 경우에 따라 다 다른 값을 가질 수 있다. (e.g. 1cm, 1m, 1km 등등)

mesh.position.x = 0.7
mesh.position.y = -0.6
mesh.position.z = 1

mesh.position.x = 0.7
mesh.position.y = -0.6
mesh.position.z = -2

position은 Vector3 로부터 상속받았다. 공식 문서를 통해 position에서 사용할 수 있는 메서드들을 확인할 수 있다.

  • length() : ${\sqrt{x^2+y^2+z^2}}$
  • distanceTo() : ${\sqrt{(x_2-x_1)^2+(y_2-y_1)^2+(z_2-z_1^2)}}$
  • normalize() : $x^2 + y^2 + z^2 = 1$

axisHelper: 축을 보여주는 오브젝트, 적색이 (양의) x,녹색이 (양의) y, 청색이 (양의) z

각 축의 기본 길이는 단위 1

mesh.position.x = 0.7
mesh.position.y = -0.6
mesh.position.z = 1
scene.add(mesh)

const axisHelper = new THREE.AxisHelper()
scene.add(axisHelper)

// ...

const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height)
camera.position.z = 3
camera.position.y = 1
camera.position.x = 1
scene.add(camera)

scale objects

x,y,z 길이를 의미 (기본은 1)

mesh.scale.x = 0.5
mesh.scale.y = 2
mesh.scale.z = 1

rotate objects

두 가지 방법

rotation

rotation은 x,y,z를 가지고 있음. Euler

꼬챙이를 끼워서 회전하는 느낌(?)

여러 축으로 회전이 되면서 축도 같이 바뀌기 때문에 이상한 모양이 나타날 수 있다. → gimal lock

reorder()로 해결

mesh.rotation.y = Math.PI * 0.25
mesh.rotation.z = Math.PI * 0.25

mesh.rotation.reorder('ZYX')
mesh.rotation.y = Math.PI * 0.25
mesh.rotation.z = Math.PI * 0.25

quaternion (4원수론)

이 역시 회전을 설명하지만, 더 수학적으로 표현

내용이 어려워서 이후 블로그에서 추가적으로 별도로 다룰 예정

Quiz

width, height, depth가 각각 1인 빨간색 정육면체를 다음과 같이 만들어 주었다. (camera.position.z = 5)

Q1. 어떻게 position 속성을 수정하면 다음 결과가 나올 것인가?

// A.
mesh.position.x = 1
mesh.position.y = -1
mesh.position.z = 1

// B.
mesh.position.x = 1
mesh.position.y = 1
mesh.position.z = -1

// C.
mesh.position.x = -1
mesh.position.y = 1
mesh.position.z = 1

// D.
mesh.position.x = 1
mesh.position.y = 1
mesh.position.z = 1

Q2. 어떻게 scale 속성을 수정하면 다음 결과가 나올 것인가?

// A.
mesh.scale.x = 0.5
mesh.scale.y = 2
mesh.scale.z = 1

// B.
mesh.scale.x = 2
mesh.scale.y = 0.5
mesh.scale.z = 1

// C.
mesh.scale.x = 0.5
mesh.scale.y = 1
mesh.scale.z = 2

// D.
mesh.scale.x = 2
mesh.scale.y = 1
mesh.scale.z = 0.5

Q3. rotate 속성을 통해 다음과 같이 수정을 해 주었다. 어떻게 수정하면 이런 결과가 나올 수 있을까?

// A.
mesh.rotation.z = Math.PI * 0.25
mesh.rotation.x = Math.PI * 0.25

// B.
mesh.rotation.y = Math.PI * 0.25
mesh.rotation.z = Math.PI * 0.25

// C.
mesh.rotation.x = Math.PI * 0.25
mesh.rotation.z = Math.PI * 0.25

// D.
mesh.rotation.x = Math.PI * 0.25
mesh.rotation.y = Math.PI * 0.25