오브젝트 움직이기

100pearlcent·2021년 9월 21일
0

Three.js

목록 보기
2/8
post-thumbnail

Scene 구성요소

  • position: 움직임
  • scale: 리사이즈
  • rotation: 회전
  • quaternion: 회전 + α

위의 네 가지 요소들은 모두 Object3D 클래스에 속한다



✨ position

position프로퍼티는 그저 오브젝트가 아닌 Vector3 클래스의 인스턴스
= 유용한 메소드가 많다

// vector 길이 구하기
console.log(mesh.position.length())

// 또 다른 vector로 부터의 거리 구하기
console.log(mesh.position.distanceTo(camera.position))

// vector 길이를 1 유닛으로 바꾸면서 방향은 유지하기
console.log(mesh.position.normalize())

// x, y, z 한꺼번에 업데이트
meesh.position.set(0.7, -0.6, 1)

✨ Scale

scale 또한 Vector3이고 x, y, z의 default 값은 1이다

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

z축은 카메라를 바라보고 있으므로 보이지 않는다
⚠️ 음수의 값은 쓰지 않는 편이 좋다


✨ Rotation

x, y, z 프로퍼티가 있다는 것은 동일하나 Vector3가 아닌 Euler

  • x축 중심으로 돌리기 ➡️ 회전목마
  • y축 중심으로 돌리기 ➡️ 차 바퀴
  • z축 중심으로 돌리기 ➡️ 프로펠러

이 축들의 값은 radian으로 표현되기 때문에 Math.PI를 사용한다

// x, y축 기준으로 1/8 회전하고 싶을 때
mesh.rotation.x = Math.PI * 0.25
mesh.rotation.y = Math.PI * 0.25

// reorder(...) 메소드를 이용해서 순서를 재정렬 할 수 있다
object.rotation.reorder('yxz')



Axes helper

포지셔닝을 돕기위한 가상의 x, y, z

// 파라미터는 선의 길이를 나타낸다
const axesHelper = new THREE.AxesHelper(2)
scene.add(axesHelper)



lookAt()

Object3D 인스턴스들은 lookAt()메서드를 사용할 수 있는데 이름 그대로 무언가를 바라보게 해준다
👉 Vector3를 파라미터로 제공하면 자동으로 -z축을 회전시켜 제공한 그 타겟을 바라보게 만든다

camera.lookAt(new THREE.Vector3(0, -1, 0))

/* mesh는 scene의 중앙에 위치하므로
default camera position에서 바라보게 한다 */
camera.lookAt(mesh.position)



Group으로 묶기

const group = new THREE.Group()
group.scale.y = 2
group.rotation.y = 0.2
scene.add(group)

const cube1 = new THREE.Mesh(
	new THREE.BoxGeometry(1, 1, 1)
  	new THREE.MeshBasicMaterial({ color: 'aliceblue'})
)
cube1.position.x = - 1.5
group.add(cube1)

const cube2 = new THREE.Mesh(
    new THREE.BoxGeometry(1, 1, 1),
    new THREE.MeshBasicMaterial({ color: 'lavenderblush' })
)
cube2.position.x = 0
group.add(cube2)

0개의 댓글