> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/camera.md).

# 카메라

플레이어의 카메라를 제어하는 방법을 알아보세요

크리에이터는 플레이어 카메라를 완전히 제어할 수 있습니다. 기본적으로 플레이어는 장면을 탐험하는 동안 1인칭 또는 3인칭 카메라 모드를 자유롭게 선택할 수 있지만, 다른 카메라 방식을 적용할 수도 있습니다.

가상 카메라는 고정형일 수도 있고, 플레이어나 다른 엔티티를 항상 바라보도록 회전할 수도 있습니다. 또는 플레이어나 다른 엔티티에 부착해 항상 함께 이동하도록 설정할 수도 있습니다.

{% hint style="warning" %}
**📔 참고**: 기본 1인칭 및 3인칭 카메라 간 전환 방법은 [카메라 수정 영역](#1st-and-3rd-person-camera-modes).
{% endhint %}

## 1인칭 및 3인칭 카메라 모드

플레이어는 일반적으로 키보드에서 V 키를 눌러 1인칭 카메라와 3인칭 카메라를 자유롭게 전환할 수 있습니다. 다음을 사용해 `CameraModeArea` 장면의 특정 영역 안에 있는 모든 플레이어의 카메라 모드를 1인칭 또는 3인칭으로 고정할 수 있습니다.

```ts
const entity = engine.addEntity()

CameraModeArea.create(entity, {
	area: Vector3.create(4, 3, 4),
	mode: CameraType.CT_FIRST_PERSON,
})
```

플레이어의 현재 카메라 모드가 `CameraModeArea`의 카메라 모드와 일치하지 않으면 해당 카메라 모드로 전환됩니다. 장면에 의해 카메라 모드가 변경되었음을 알리는 토스트 메시지가 화면에 표시됩니다. 영역 안에 있는 동안 플레이어는 카메라 모드를 변경할 수 없습니다. 플레이어가 `CameraModeArea`을 벗어나면 진입하기 전에 사용하던 카메라 모드로 복원됩니다.

플레이어가 특정 카메라 모드를 사용할 때 경험이 크게 향상되는 영역에서 `CameraModeArea` 를 사용하세요. 예를 들어 플레이어가 작은 물체를 클릭해야 한다면 1인칭 시점이 적합하고, 장면에 플레이어의 머리 위에 붙어 있는 엔티티를 알아차리게 하려면 3인칭 시점이 유용할 수 있습니다. 플레이어가 카메라 모드를 전환하는 방법을 안다고 가정하지 마세요. 처음 플레이하는 사람 중에는 그런 기능이 있는지 모르거나 전환 키를 기억하지 못하는 경우가 많습니다.

{% hint style="warning" %}
**📔 참고**: 카메라 수정 영역은 다음의 영향을 받습니다. *위치* 및 *회전* 호스트 엔티티의 Transform 컴포넌트의 영향을 받지만, 다음의 영향은 받지 않습니다. *크기*.
{% endhint %}

{% hint style="warning" %}
**📔 참고**: 카메라 수정 영역이 여러 개 겹치면, 씬 코드에서 가장 마지막에 인스턴스화된 영역이 다른 영역보다 우선 적용됩니다.
{% endhint %}

다음을 생성할 때 `CameraModeArea` 컴포넌트에는 다음을 제공해야 합니다:

* `area`: 수정 영역의 크기
* `mode`: 이 영역에서 강제할 카메라 모드입니다. 다음 `CameraType` 열거형에서 선택합니다.

지원되는 카메라 모드는 다음과 같습니다:

* `CameraType.CT_FIRST_PERSON`
* `CameraType.CT_THIRD_PERSON`

### 카메라 모드 조회

다음을 사용해 플레이어의 카메라 모드를 조회할 수 있습니다. `CameraMode` 컴포넌트를 `engine.CameraEntity`.

```ts
const cameraMode = CameraMode.get(engine.CameraEntity)
if (cameraMode.mode === CameraType.CT_FIRST_PERSON) {
	console.log('The player is using the 1st person camera')
} else {
	console.log('The player is using the 3rd person camera')
}
```

다음을 사용해 카메라 모드 변경을 구독할 수도 있습니다. `onChange` 함수는 `CameraMode` 컴포넌트에 있습니다.

```ts
CameraMode.onChange(engine.CameraEntity, (cameraMode) => {
	if (!cameraMode) return
	console.log('The player\'s camera mode changed to', cameraMode.mode)
})
```

## 가상 카메라 사용

씬에서 사용자 지정 카메라 동작을 사용하려면 다음 두 가지가 필요합니다.

* 가상 카메라 만들기: 씬에 엔티티를 만들고 다음을 지정합니다. `VirtualCamera`.
* 가상 카메라 할당하기: 예약된 엔티티 `MainCamera` 컴포넌트를 다음에 추가합니다. [예약된 엔티티](https://docs.decentraland.org/creator/content-creator-ko/sdk7/architecture/entities-components.md#reserved-entities) `engine.CameraEntity`. 그리고 `VirtualCamera` 컴포넌트가 있는 엔티티를 참조하도록 설정합니다.

그러면 카메라가 다음 컴포넌트가 있는 엔티티에 연결됩니다. `VirtualCamera` 컴포넌트. 엔티티가 이동하거나 회전하면 카메라도 함께 이동합니다.

```ts
function main() {
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera, {})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})
}
```

이 예시에서 플레이어가 씬의 경계 안에 있는 동안 카메라는 항상 씬의 고정된 위치에 머뭅니다. 플레이어가 씬 경계 밖으로 나가는 즉시 기본 카메라 동작이 복원됩니다.

### 시야각

가상 카메라의 시야각(FOV)은 다음 속성을 사용해 도 단위로 설정합니다. `fov` 속성입니다. 이 값은 해당 가상 카메라가 활성화된 동안에만 적용됩니다.

```ts
const cinematicCamera = engine.addEntity()
Transform.create(cinematicCamera, {
	position: Vector3.create(8, 3, 2),
})
VirtualCamera.create(cinematicCamera, {
	fov: 45,
})
```

FOV가 좁으면(값이 낮으면) 확대되어 컷신이나 조준에 유용합니다. FOV가 넓으면(값이 높으면) 씬을 더 많이 보여 주므로 파노라마 뷰에 유용합니다.

{% hint style="warning" %}
**📔 참고**: 생성하는 모든 가상 카메라에 `fov` 를 설정하세요. 이 값을 생략한다고 해서 중립적인 60도가 적용되는 것은 아닙니다. 클라이언트는 렌즈를 초기화하지 않은 채 풀링된 카메라 인스턴스를 재사용하므로, `fov` 값이 없는 카메라는 해당 인스턴스에 이전 카메라가 설정한 시야각을 그대로 유지합니다. 넓은 항공 뷰를 보여 주려는 카메라가 시작부터 크게 확대된 상태일 수도 있습니다.
{% endhint %}

씬에는 원하는 만큼 다음 컴포넌트가 있는 엔티티를 포함할 수 있습니다. `VirtualCamera`컴포넌트를 포함한 엔티티를 원하는 만큼 만들 수 있으며, 플레이어의 이동이나 특정 동작에 따라 여러 가상 카메라 간에 동적으로 전환할 수 있습니다. 한 번에 하나의 가상 카메라만 활성화되며, 활성 카메라는 다음 항목에서 지정합니다. `MainCamera` 컴포넌트는 다음에 있습니다. `engine.CameraEntity`.

기본 카메라 동작으로 되돌리려면 값을 `undefined` 로 `MainCamera.virtualCameraEntity`설정합니다. 그러면 플레이어가 1인칭 카메라와 3인칭 카메라 사이를 자유롭게 전환할 수 있습니다. 플레이어가 이 두 모드 중 하나만 사용하게 하려면 [카메라 수정 영역](#1st-and-3rd-person-camera-modes) 을 사용해 둘 중 하나로 고정할 수 있습니다.

{% hint style="warning" %}
**📔 참고**: 카메라를 해제할 때는 `undefined`를 사용해야 하며, `0`를 사용하면 안 됩니다. 값이 없는 경우에만 플레이어에게 제어권이 돌아갑니다. 값이 `0` 인 `engine.RootEntity`에는 `VirtualCamera`가 없으므로, 엔진은 마지막으로 활성화된 가상 카메라를 계속 사용하고 플레이어는 해당 시점에 고정됩니다.

카메라를 저장했다가 복원하는 코드에서 이 문제가 발생할 수 있습니다.  `virtualCameraEntity` 는 선택적이며 새 `undefined` 의 `MainCamera`에서는 `?? 0`  또는  `|| 0` 를 대체 값으로 사용하면 이 값이 `0` 로 바뀌어 나중에 다시 기록됩니다. 복원하기 전에 엔티티가 있는지 확인하세요.

```ts
function restoreCamera(previous: Entity | undefined) {
	const camera = MainCamera.getMutableOrNull(engine.CameraEntity)
	if (!camera) return
	// 실제로 존재하는 카메라만 복원하고, 그렇지 않으면 제어권을 해제합니다
	camera.virtualCameraEntity = previous && VirtualCamera.has(previous) ? previous : undefined
}
```

{% endhint %}

{% hint style="warning" %}
**📔 참고**: 카메라 수정 영역은 활성화된 가상 카메라가 없을 때만 플레이어에게 영향을 줍니다. 장면에서 현재 가상 카메라를 사용 중일 때 플레이어가 카메라 수정 영역에 들어가도 아무 일도 일어나지 않습니다.

3D 모델의 콘텐츠에 `camera` 노드가 포함되어 있으면 SDK에서 사용할 수 없습니다. 모든 카메라는 SDK를 사용해 엔티티로 만들어야 합니다.
{% endhint %}

```ts
function main() {
	// 사용자 지정 가상 카메라
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera, {})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})

	// 클릭 가능한 큐브
	const clickCube = engine.addEntity()
	Transform.create(clickCube, { position: Vector3.create(8, 0, 8) })
	MeshRenderer.setBox(clickCube)
	MeshCollider.setBox(clickCube)
	pointerEventsSystem.onPointerDown(
		{
			entity: clickCube,
			opts: { button: InputAction.IA_POINTER, hoverText: '카메라 초기화' },
		},
		() => {
			// 카메라를 기본 동작으로 초기화
			const mainCamera = MainCamera.getMutable(engine.CameraEntity)
			mainCamera.virtualCameraEntity = undefined
		}
	)
}
```

{% hint style="info" %}
**💡 팁**: 카메라가 아바타에서 멀어질 때는 아바타의 움직임도 멈추는 것이 좋습니다. 그러면 플레이어가 앞을 보지 못한 채 장애물에 부딪히는 일을 방지할 수 있습니다. 자세한 내용은 다음을 참조하세요. [입력 수정자](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/avatars/locomotion.md#freeze-the-player)
{% endhint %}

플레이어가 마우스로 가상 카메라를 조작하게 하려면 `screenDelta` 속성을 읽어 `PrimaryPointerInfo` 컴포넌트에서 매 프레임 커서가 얼마나 움직였는지 확인한 다음, 그 움직임을 카메라 회전에 적용하세요. 커서가 잠겨 있어도 작동합니다. 전체 마우스 시점 조작 예시는 [마우스 움직임](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/mouse-movement.md) 을 참조하세요.

## 조감도

가상 카메라를 사용하면 장면을 위에서 내려다볼 수 있습니다. 아바타의 일반적인 시점과 다른 재미있는 변화를 줄 수 있으며, 다양한 게임 메커니즘을 구현할 수도 있습니다.

카메라가 완전히 수직으로 아래를 향하도록 배치하지 않는 것이 좋습니다. 대신 카메라를 항상 약간 기울이세요. 1도만 기울여도 충분합니다. 플레이어의 방향 조작은 아바타의 방향이 아니라 카메라의 시점을 기준으로 하기 때문입니다. 카메라가 완벽한 조감도를 바라보면 어느 쪽이 어느 방향인지 명확히 정의할 수 없습니다. 알아차리기 어려울 정도인 1도의 기울기만으로도 전방 방향을 설정할 수 있습니다.

```ts
function main() {
	// 조감도 카메라
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(8, 5, 8),
		rotation: Quaternion.fromEulerDegrees(91, 0, 0),
		// 회전 값이 90º가 아니라 91º임에 유의하세요
	})
	VirtualCamera.create(myCustomCamera, {})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})
}
```

## 시야각

가상 카메라의 시야각(FOV)은 `fov` 속성으로 설정할 수 있습니다. 값의 단위는 도입니다. 항상 값을 설정하세요. 기본값이 없으므로, `fov` 를 지정하지 않은 카메라는 동일한 풀링 인스턴스를 사용했던 이전 카메라의 렌즈 설정을 이어받습니다.

```ts
VirtualCamera.create(myCustomCamera, {
	fov: 90,
})
```

시야각을 넓히면(값이 커지면) 한 번에 더 많은 장면이 보이고 속도감이 생기므로 레이싱 게임에 유용할 수 있습니다. 시야각을 좁히면(값이 작아지면) 확대되므로 조준이나 영화 같은 장면에 적합합니다.

### 줌 수준 변경

클라이언트는 카메라가 활성화되는 순간에만 `fov` 를 읽습니다. 이미 활성화된 카메라의 `fov` 를 변경해도 아무런 효과가 없습니다.

확대/축소하려면 줌 수준마다 가상 카메라를 하나씩 만들고 `MainCamera.virtualCameraEntity` 를 전환하세요.

```ts
import { engine, MainCamera, Transform, VirtualCamera } from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

// 같은 위치에 있는 두 카메라. 하나는 광각이고 다른 하나는 확대된 시점입니다.
const position = Vector3.create(8, 2, 8)

const wideCamera = engine.addEntity()
Transform.create(wideCamera, { position })
VirtualCamera.create(wideCamera, { fov: 70 })

const zoomedCamera = engine.addEntity()
Transform.create(zoomedCamera, { position })
VirtualCamera.create(zoomedCamera, { fov: 30 })

// 확대/축소하려면 두 카메라를 전환합니다.
function zoomIn() {
	MainCamera.createOrReplace(engine.CameraEntity, { virtualCameraEntity: zoomedCamera })
}

function zoomOut() {
	MainCamera.createOrReplace(engine.CameraEntity, { virtualCameraEntity: wideCamera })
}
```

이미 활성화된 카메라를 다시 지정해도 아무런 효과가 없으므로, 매번 다른 엔터티로 전환하세요.

## 카메라 전환

장면에서 가상 카메라 간에 전환하거나 기본 카메라 동작과 가상 카메라 간에 전환할 때마다 플레이어에게 전환 효과가 표시됩니다. 가상 카메라의 위치, 회전 및 기타 매개변수가 일정 시간에 걸쳐 부드럽게 바뀝니다.

가상 카메라의 전환 설정은 다음 카메라로 전환되는 방식을 결정합니다. *로* 장면의 다른 카메라(기본 카메라 포함)에서 해당 카메라로 전환하는 방식에는 영향을 주지 않습니다. 전환 방식은 *종료* 하는 카메라에 따라 달라집니다.

플레이어의 카메라로 돌아가서 `virtualCameraEntity` 의 `MainCamera`를 비우면 항상 0.5초 동안 고정된 전환이 적용되며, 전환은 부드럽게 시작하고 끝납니다. `defaultTransition` 은 떠나는 가상 카메라의 값과 관계없이 동일합니다.

```ts
VirtualCamera.create(myCustomCamera1, {
	defaultTransition: { transitionMode: VirtualCamera.Transition.Time(6) },
})
```

{% hint style="info" %}
**💡 팁**: 전환 없이 카메라를 즉시 바꾸려면 전환 시간이나 속도를 0으로 설정하세요.
{% endhint %}

사용 사례에 따라 전환 시간을 설정하는 대신 전환 속도를 설정하는 편이 나을 수 있습니다.

* **고정 시간**: 전환 지속 시간을 설정하면 카메라는 지정된 시간 안에 경로를 완료하는 데 필요한 속도로 이동합니다.
* **고정 속도**: 전환 중 가상 카메라의 이동 속도를 설정합니다. 전환 시간은 이동 거리에 따라 달라집니다. 속도 값은 다음 단위로 해석됩니다. **초당 미터**.

아래는 두 전환 모드의 예입니다.

```ts
// 고정 지속 시간
VirtualCamera.create(myCustomCamera1, {
	defaultTransition: { transitionMode: VirtualCamera.Transition.Time(6) },
})

// 고정 속도
VirtualCamera.create(myCustomCamera1, {
	defaultTransition: { transitionMode: VirtualCamera.Transition.Speed(3) },
})
```

아래는 가상 카메라 두 대와 그 사이의 전환을 보여주는 전체 예제입니다.

```ts
function main() {
	// 사용자 지정 가상 카메라 1
	const myCustomCamera1 = engine.addEntity()
	Transform.create(myCustomCamera1, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera1, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(1) },
	})

	// 사용자 지정 가상 카메라 2
	const myCustomCamera2 = engine.addEntity()
	Transform.create(myCustomCamera2, {
		position: Vector3.create(1, 2, 1),
	})
	VirtualCamera.create(myCustomCamera2, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(3) },
	})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera1,
	})

	// 클릭 가능한 큐브
	const clickCube = engine.addEntity()
	Transform.create(clickCube, { position: Vector3.create(8, 0, 8) })
	MeshRenderer.setBox(clickCube)
	MeshCollider.setBox(clickCube)
	pointerEventsSystem.onPointerDown(
		{
			entity: clickCube,
			opts: { button: InputAction.IA_POINTER, hoverText: '카메라 초기화' },
		},
		() => {
			// 카메라를 기본 동작으로 초기화
			const mainCamera = MainCamera.getMutable(engine.CameraEntity)
			mainCamera.virtualCameraEntity =
				mainCamera.virtualCameraEntity == myCustomCamera1
					? myCustomCamera2
					: myCustomCamera1
		}
	)
}
```

전환은 경로상의 장애물을 고려하지 않고 항상 직선으로 이동합니다. 대신 다른 가상 카메라를 중간 매개체로 사용해 전환을 직접 만들 수도 있습니다. 그러면 이동을 완전히 제어할 수 있습니다. 이 중간 가상 카메라로 [트윈](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/move-entities.md#move-between-two-points) 을 사용해 첫 번째 카메라의 위치에서 두 번째 카메라의 위치까지 이동하거나, 장애물을 피하거나 영화 같은 우회 경로를 따르는 등 원하는 경로를 지정할 수 있습니다.

## 카메라 추적

가상 카메라가 항상 플레이어 또는 장면의 특정 엔티티가 향하는 방향을 바라보도록 설정할 수 있습니다. 카메라의 위치는 고정된 채 회전만 바뀌어 해당 엔티티가 항상 화면 중앙에 오도록 합니다.

이 기능은 `lookAtEntity` 속성을 사용해 `VirtualCamera` 컴포넌트에서 구현할 수 있습니다. 플레이어를 추적하려면 [예약된 엔티티를](https://docs.decentraland.org/creator/content-creator-ko/sdk7/architecture/entities-components.md#reserved-entities) `engine.PlayerEntity`.

```ts
const myCustomCamera1 = engine.addEntity()
Transform.create(myCustomCamera1, {
	position: Vector3.create(1, 2, 1),
})
VirtualCamera.create(myCustomCamera1, {
	lookAtEntity: engine.PlayerEntity,
})
```

카메라가 엔티티를 따라가는 경우, 이 설정은 카메라의 위치가 아니라 회전만 변경합니다.

카메라가 회전해도 다음 컴포넌트가 있는 엔티티의 Transform은 `VirtualCamera` 변경되지 않습니다. 하지만 다음의 Transform에서 카메라의 회전을 읽을 수 있습니다. `engine.CameraEntity`. 이 엔티티의 회전과 위치는 절대적이며, 다음 컴포넌트가 있는 엔티티의 영향을 받지 않습니다. `VirtualCamera` 이 Transform의 회전은 `lookAtEntity` 동작에 따라 변경됩니다.

{% hint style="warning" %}
**📔 참고**: 가상 카메라의 `lookAtEntity` 에 가상 카메라가 있는 엔티티 자체 또는 `engine.CameraEntity` 엔티티를 지정하면, 엔티티를 지정하지 않은 경우와 동일하게 동작합니다.
{% endhint %}

## 플레이어에 연결하기

가상 카메라를 플레이어 엔티티에 연결하면 사용자 지정 거리나 각도에서 플레이어를 따라가도록 할 수 있습니다. 플레이어가 카메라의 회전을 자유롭게 바꿀 수 없으므로, 이 경우 카메라의 회전은 가상 카메라의 회전으로 고정됩니다. 예를 들어 플레이어가 항상 앞을 바라봐야 하는 레이싱 게임에서 유용하게 사용할 수 있습니다.

```ts
function main() {
	const myCustomCamera = engine.addEntity()
	Transform.create(myCustomCamera, {
		position: Vector3.create(0, 1, 5),
		parent: engine.PlayerEntity,
	})
	VirtualCamera.create(myCustomCamera, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(2) },
	})

	const mainCamera = MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: myCustomCamera,
	})
}
```

## 카메라와 콜라이더

3인칭 모드에서 플레이어의 카메라가 이동할 때, 엔티티에 할당된 충돌 레이어에 따라 콜라이더에 가로막힐 수도 있고 그렇지 않을 수도 있습니다. 장면을 설계할 때 이 점을 고려해야 합니다. 카메라가 벽이나 다른 엔티티를 통과하지 않도록 설정할 수 있습니다.

자세한 내용은 [콜라이더](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/colliders.md#cameras-and-colliders) 문서에서 장면의 콜라이더를 설정하는 방법을 확인하세요.

## 관전 모드(관전자 카메라)

플레이어를 일반 아바타 이동에서 자유 이동 카메라 또는 플레이어 추적 카메라로 전환하는 관전 모드를 만들 수 있습니다. 경쟁 게임의 관전자 역할, 라이브 이벤트의 연출 카메라 또는 리플레이 시스템에 유용합니다.

이 패턴은 여러 SDK 기능을 조합합니다.

| 기능           | SDK API                                   | 용도                            |
| ------------ | ----------------------------------------- | ----------------------------- |
| 사용자 지정 카메라 뷰 | `VirtualCamera` + `MainCamera`            | 플레이어의 카메라를 대체합니다              |
| 아바타 이동 정지    | `InputModifier` (`disableAll: true`)      | 카메라 조작에 WASD 키를 사용할 수 있도록 합니다 |
| 장면의 플레이어 추적  | `onEnterScene` / `onLeaveScene`           | 추적 대상 목록을 만듭니다                |
| 카메라 조작       | `inputSystem.isPressed(InputAction.IA_*)` | WASD로 상하/좌우 회전, E/F로 확대/축소    |
| 마우스로 시점 조작   | `PrimaryPointerInfo.screenDelta`          | 마우스로 카메라 회전                   |

### 카메라 리그 아키텍처

다음과 같이 **두 엔티티 리그** 를 사용하면 요와 피치가 서로 독립적으로 유지됩니다.

```
rigRoot (entity)           -- 월드 위치 + 요 회전
└── rigCamera (child)      -- 피치 회전 + 궤도 오프셋
    └── VirtualCamera
```

`rigRoot` 은 요(좌우 회전)를 담당하며, 추적 대상이나 자유 카메라의 피벗을 향해 보간됩니다. `rigCamera` 는 피치(상하 기울기)와 루트에서 떨어진 궤도 거리를 처리합니다. 두 Transform에 요와 피치를 분리하면 오일러 각 계산이 간단해집니다.

### 활성화 및 비활성화

```ts
// 관전 모드 활성화
const rigRoot = engine.addEntity()
Transform.create(rigRoot, {
  position: Vector3.create(8, 8, 8),
  rotation: Quaternion.fromEulerDegrees(0, 0, 0),
})

const rigCamera = engine.addEntity()
Transform.create(rigCamera, { parent: rigRoot })
VirtualCamera.create(rigCamera, {})

MainCamera.createOrReplace(engine.CameraEntity, { virtualCameraEntity: rigCamera })
InputModifier.createOrReplace(engine.PlayerEntity, {
  mode: InputModifier.Mode.Standard({ disableAll: true }),
})
```

```ts
// 관전 모드 비활성화
// 중요: VirtualCamera 엔티티를 제거하기 전에 MainCamera를 초기화하세요.
// 엔티티를 먼저 제거하면 엔진은 이미 사라진 엔티티에 계속 바인딩됩니다.
// 그러면 시점이 플레이어의 발밑으로 이동합니다.
const mainCamera = MainCamera.getMutableOrNull(engine.CameraEntity)
if (mainCamera) mainCamera.virtualCameraEntity = undefined

engine.removeEntity(rigCamera)
engine.removeEntity(rigRoot)

InputModifier.createOrReplace(engine.PlayerEntity, {
  mode: InputModifier.Mode.Standard({ disableAll: false }),
})
```

{% hint style="danger" %}
**경고:** 카메라 엔티티를 제거하기 전에 항상 `MainCamera.virtualCameraEntity` 를 초기화하세요. 엔티티를 먼저 제거하면 엔진이 이미 사라진 참조를 가리키게 되어 시점이 제대로 작동하지 않습니다.
{% endhint %}

### 카메라 경계

엔진은 `VirtualCamera` 엔티티가 씬의 필지 경계 밖으로 이동하면 비활성화합니다. 카메라가 씬 영역을 벗어나면 아무런 알림 없이 작동을 멈춥니다. 매 프레임 카메라 위치를 씬의 축 정렬 경계 상자(AABB) 안에 있도록 제한하고, 약간의 여유 공간을 두세요.

```ts
// 1x1 필지 씬(16m x 16m)의 경계 예시
const BOUNDS_MIN = Vector3.create(0, 0, 0)
const BOUNDS_MAX = Vector3.create(16, 20, 16)
const BOUNDS_MARGIN = 0.5
```

더 큰 씬에서는 경계를 `scene.json` 의 필지에 맞게 설정하세요. 필지 수와 관계없이 씬 높이 제한은 330미터입니다. 4x4 필지 씬에는 다음 값을 사용할 수 있습니다. `Vector3.create(64, 330, 64)`.

### 플레이어 따라가기

다음을 사용하세요. `onEnterScene` 및 `onLeaveScene` 장면에 있는 플레이어 목록을 실시간으로 구성합니다. 그러면 플레이어가 키(예: `IA_ACTION_3` 및 `IA_ACTION_4`)를 사용해 관전 대상을 순환하며 선택할 수 있습니다. 플레이어를 관전하는 동안 리그 루트는 관전 대상 플레이어의 Transform 위치를 향해 보간되고, 자식 카메라는 설정 가능한 거리에서 궤도를 따라 움직입니다.

```ts
import { onEnterScene, onLeaveScene } from '@dcl/sdk/src/players'

const playerEntities = new Map<string, Entity>()
let playerIds: string[] = []

onEnterScene((player) => {
  if (!player) return
  playerIds.push(player.userId)
  playerEntities.set(player.userId, player.entity)
})

onLeaveScene((userId) => {
  if (!userId) return
  playerIds = playerIds.filter((id) => id !== userId)
  playerEntities.delete(userId)
})
```

매 프레임 플레이어를 관전하려면 리그 루트를 해당 플레이어의 위치를 향해 보간합니다.

```ts
const followEntity = playerEntities.get(followTargetId)
if (followEntity) {
  const targetPos = Transform.get(followEntity).position
  const rootTransform = Transform.getMutable(rigRoot)
  rootTransform.position = Vector3.lerp(
    rootTransform.position,
    Vector3.add(targetPos, Vector3.create(0, 1, 0)),
    0.1
  )
}
```

자세한 내용은 [플레이어가 장면에 들어오거나 나갈 때](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/event-listeners.md#player-enters-or-leaves-scene) 에서 `onEnterScene` 및 `onLeaveScene`.

### 관전 중 마우스로 시점 조작

매 프레임 `PrimaryPointerInfo.screenDelta` 를 읽어 마우스로 카메라를 회전합니다. 포인터가 잠겨 있을 때도 작동합니다. 자세한 내용은 [마우스 이동](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/mouse-movement.md) 에서 마우스 시점 조작의 전체 예제를 확인하세요.

```ts
const MOUSE_SENSITIVITY = 0.15 // 픽셀당 각도
let yaw = 0
let pitch = 45

function spectateMouseLook() {
  const isLocked = PointerLock.getOrNull(engine.CameraEntity)?.isPointerLocked ?? false
  if (!isLocked) return

  const delta = PrimaryPointerInfo.getOrNull(engine.RootEntity)?.screenDelta
  if (!delta) return

  yaw = (yaw + delta.x * MOUSE_SENSITIVITY) % 360
  // delta.y는 아래쪽으로 갈수록 커지므로, 마우스를 위로 움직이면 음수입니다. 이를 더하면 카메라가 위쪽으로 기울어집니다. 뒤집히지 않도록 범위를 제한합니다.
  pitch = Math.max(-25, Math.min(80, pitch + delta.y * MOUSE_SENSITIVITY))
}
```

{% hint style="warning" %}
**참고:** `screenDelta` 는 데스크톱 전용입니다. 모바일에서는 항상 `0`. 장면이 모바일을 대상으로 한다면 터치 기반 대체 방식을 설계하세요.
{% endhint %}

### 전체 참조 구현

&#x20;[`33,20-spectate-mode`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/33,20-spectate-mode)  테스트 장면에는 다음 파일에 독립적으로 사용할 수 있는 관전 모듈이 포함되어 있습니다:  `src/spectate.ts`. 이 모듈은 자유 시점 및 따라가기 시점 모드, WASD 및 마우스 시점 조작, 플레이어 전환, 궤도 거리 확대·축소, 경계 제한을 지원하며, 조작 방법과 현재 따라가는 대상을 표시하는 화면 HUD를 제공합니다.

자신의 프로젝트에서 사용하려면 다음을 따르세요.

1. 복사 `src/spectate.ts` 를 장면에 추가합니다.
2. 파일 상단의 `PIVOT`, `BOUNDS_MIN`및 `BOUNDS_MAX` 를 장면의 구획에 맞게 수정합니다. 통합 과정에서 가장 흔히 발생하는 실수입니다.
3. 다음 함수 `toggleSpectate()` 를 클릭 가능한 엔티티, UI 버튼, 키 입력 등 원하는 트리거에 연결합니다.

{% hint style="info" %}
**💡 팁**: 카메라 제어의 작동 예제는 다음을 참조하세요: 여러 [`2,22-virtual-cameras`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/2,22-virtual-cameras) 테스트 장면에서는 여러 `VirtualCamera` 엔티티를 `MainCamera` 로 전환하며, 플레이어를 바라보는 `lookAtEntity` 와 트윈 카메라를 포함합니다; [`32,20-virtual-camera-mouse-look`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/32,20-virtual-camera-mouse-look): 포인터가 잠겨 있는 동안 마우스 시점 카메라를 작동합니다; [`33,20-spectate-mode`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/33,20-spectate-mode): 따라가기 시점 및 자유 시점 모드를 제공하는 완전한 관전 카메라를 구현합니다; 그리고 [`9,99-modifier-areas`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/9,99-modifier-areas): 볼륨 안에서 카메라 모드를 강제로 적용하며, `CameraModeArea`.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/camera.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
