> 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/interactivity/mouse-movement.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 마우스 움직임

플레이어의 마우스 움직임에 실시간으로 반응하여 드래그 제스처를 구현하거나, 오브젝트를 회전시키거나, 커스텀 카메라를 제어하세요.

씬은 매 프레임 플레이어의 원시 마우스 움직임을 읽어 실시간 상호작용에 활용할 수 있습니다. 드래그 및 스와이프 제스처, 플레이어가 드래그할 때 회전하거나 미끄러지는 오브젝트, 1인칭 슈팅 게임처럼 직접 만든 카메라 조작 등이 가능합니다.

이렇게 하려면 `screenDelta` 속성을 읽으세요. 이 속성은 `PrimaryPointerInfo` 컴포넌트에 있으며, `engine.RootEntity`에서 가져올 수 있습니다. 이 속성은 마우스가 지난 프레임 이후 몇 픽셀 이동했는지 알려 주는 `Vector2` 입니다. 양수 `x` 값은 마우스가 오른쪽으로 움직였음을, 양수 `y` 값은 아래쪽으로 움직였음을 뜻합니다. 이는 화면의 원점이 왼쪽 위 모서리인 것과 일치하며, `UiTransform` 및 `UiCanvasInformation`과 같은 좌표 공간을 사용합니다. 마우스가 움직이지 않은 프레임에서는 두 값이 모두 0입니다.

```ts
import { engine, PrimaryPointerInfo } from '@dcl/sdk/ecs'

engine.addSystem(() => {
	const delta = PrimaryPointerInfo.getOrNull(engine.RootEntity)?.screenDelta
	if (!delta) return
	console.log(`mouse moved: ${delta.x}, ${delta.y}`)
})
```

screenDelta `에는 한 프레임 동안의 움직임만 저장되므로,` 프레임 사이의 움직임을 놓치지 않도록 항상 [시스템](https://docs.decentraland.org/creator/content-creator-ko/sdk7/architecture/systems.md)안에서 읽으세요.

{% hint style="warning" %}
**📔 참고**: 씬 로딩 초기에 `engine.RootEntity` 를 참조하지 마세요. 엔티티가 아직 초기화되지 않았으면 오류가 발생할 수 있습니다. 이 문제를 방지하려면 항상 시스템 안에서 해당 엔티티를 참조하세요. 시스템이 처음 실행되는 시점에는 씬이 이미 올바르게 초기화되어 있으므로 엔티티를 사용할 수 있습니다.
{% endhint %}

{% hint style="warning" %}
**📔 참고**: 이 문서의 내용은 데스크톱 플레이어에게만 해당합니다. 모바일 앱에서는 입력이 터치 기반이고 자유롭게 움직이는 커서가 없으므로 [모바일 앱](https://docs.decentraland.org/creator/content-creator-ko/build-for-mobile/mobile-client/overview.md)에서 `screenDelta` 는 항상 0을 보고합니다. 터치 기기에서 입력이 작동하는 방식은 [모바일 입력](https://docs.decentraland.org/creator/content-creator-ko/build-for-mobile/develop/input-on-mobile.md) 을, 모바일 플레이어에게 대체 조작 방식을 제공하는 방법은 [플랫폼 감지](https://docs.decentraland.org/creator/content-creator-ko/build-for-mobile/develop/detect-platform.md) 을 참고하세요.
{% endhint %}

## 커서가 잠긴 상태에서의 마우스 움직임

`screenDelta` 는 커서가 `잠겨` 있을 때 [PrimaryPointerInfo](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/button-events/click-events.md#lock-or-unlock-the-cursor): `의 다른 속성과 다르게 작동합니다.` screenCoordinates `는 화면 중앙에서 고정되고,` worldRayDirection 는 항상 화면 중앙의 광선 방향을 보고하지만 `screenDelta` 는 매 프레임마다 가공되지 않은 마우스 이동량을 계속 보고합니다. 따라서 커서가 잠겨 있는 동안 마우스 이동량을 읽을 수 있는 유일한 방법이며, 사용자 지정 카메라나 조준 컨트롤을 구현할 때 꼭 필요합니다.

## 드래그하여 오브젝트 회전하기

다음 예제에서는 플레이어가 포인터 버튼을 누른 상태에서 마우스를 좌우로 드래그하여 큐브를 회전할 수 있습니다.

```ts
import {
	engine,
	InputAction,
	inputSystem,
	MeshCollider,
	MeshRenderer,
	PrimaryPointerInfo,
	Transform,
} from '@dcl/sdk/ecs'
import { Quaternion, Vector3 } from '@dcl/sdk/math'

const DRAG_SENSITIVITY = 0.5

export function main() {
	const cube = engine.addEntity()
	Transform.create(cube, { position: Vector3.create(8, 1, 8) })
	MeshRenderer.setBox(cube)
	MeshCollider.setBox(cube)

	engine.addSystem(() => {
		// 포인터 버튼을 누르고 있는 동안에만 회전
		if (!inputSystem.isPressed(InputAction.IA_POINTER)) return

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

		const transform = Transform.getMutable(cube)
		transform.rotation = Quaternion.multiply(
			transform.rotation,
			Quaternion.fromEulerDegrees(0, delta.x * DRAG_SENSITIVITY, 0)
		)
	})
}
```

같은 패턴을 모든 드래그 상호작용에 사용할 수 있습니다. 예를 들어 `delta.x` 를 오프셋으로 사용하여 엔티티를 레일을 따라 이동하거나, 애니메이션을 스크러빙하거나, 큰 델타 값을 확인하여 빠른 스와이프를 감지할 수 있습니다.

## 마우스 시점 카메라 컨트롤

커서가 잠겨 있어도 `screenDelta` 가 계속 작동하므로 이를 사용하여 [가상 카메라](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/camera.md#using-virtual-cameras)의 마우스 시점 컨트롤을 만들 수 있습니다. 이를 위해 마우스 이동량을 요 및 피치 각도에 누적한 다음, 매 프레임마다 카메라의 회전에 적용합니다.

다음 예제에서 플레이어는 상자를 클릭하여 마우스로 조종할 수 있는 가상 카메라로 전환하고, 보조 버튼(*F*  또는 마우스 오른쪽 버튼)을 눌러 기본 카메라로 돌아갑니다. 가상 카메라가 활성화되어 있는 동안에는 장면에서 커서를 잠그고 [입력 수정자](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/avatars/locomotion.md#freeze-the-player)로 아바타를 고정하여, 플레이어가 카메라를 조종하는 동안 보이지 않는 곳에서 아바타가 돌아다니지 않도록 합니다.

```ts
import {
	engine,
	Entity,
	InputAction,
	InputModifier,
	inputSystem,
	MainCamera,
	MeshCollider,
	MeshRenderer,
	PointerEventType,
	pointerEventsSystem,
	PointerLock,
	PrimaryPointerInfo,
	Transform,
	VirtualCamera,
} from '@dcl/sdk/ecs'
import { Quaternion, Vector3 } from '@dcl/sdk/math'

// 마우스 이동 픽셀당 카메라 회전 각도
const SENSITIVITY = 0.15

let cameraEntity: Entity
let cameraActive = false
let yaw = 0
let pitch = 0

export function main() {
	// 카메라가 따라가는 엔티티
	cameraEntity = engine.addEntity()
	Transform.create(cameraEntity, { position: Vector3.create(8, 3, 8) })
	VirtualCamera.create(cameraEntity, {
		defaultTransition: { transitionMode: VirtualCamera.Transition.Time(0.5) },
	})

	// 이 상자를 클릭하여 마우스 시점 제어 모드로 진입
	const box = engine.addEntity()
	Transform.create(box, { position: Vector3.create(8, 1, 4) })
	MeshRenderer.setBox(box)
	MeshCollider.setBox(box)
	pointerEventsSystem.onPointerDown(
		{
			entity: box,
			opts: { button: InputAction.IA_POINTER, hoverText: 'Control camera' },
		},
		() => activateCamera(true)
	)

	// 마우스로 카메라 조작
	engine.addSystem(() => {
		if (!cameraActive) return
		if (!PointerLock.getOrNull(engine.CameraEntity)?.isPointerLocked) return

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

		yaw += delta.x * SENSITIVITY
		// 카메라가 뒤집히지 않도록 피치 제한
		pitch = Math.max(-85, Math.min(85, pitch + delta.y * SENSITIVITY))

		Transform.getMutable(cameraEntity).rotation = Quaternion.fromEulerDegrees(pitch, yaw, 0)
	})

	// 보조 버튼으로 마우스 시점 제어 모드 종료
	engine.addSystem(() => {
		if (!cameraActive) return
		if (inputSystem.isTriggered(InputAction.IA_SECONDARY, PointerEventType.PET_DOWN)) {
			activateCamera(false)
		}
	})
}

function activateCamera(active: boolean) {
	cameraActive = active

	// 가상 카메라 할당 또는 해제
	MainCamera.createOrReplace(engine.CameraEntity, {
		virtualCameraEntity: active ? cameraEntity : undefined,
	})

	// 카메라를 조작하는 동안 아바타 고정
	InputModifier.createOrReplace(engine.PlayerEntity, {
		mode: InputModifier.Mode.Standard({ disableAll: active }),
	})

	// 마우스로 즉시 카메라를 조작할 수 있도록 커서 잠금
	PointerLock.createOrReplace(engine.CameraEntity, { isPointerLocked: active })
}
```

이 예제에서 주의할 사항은 다음과 같습니다.

* 시스템은  `delta.y` 를 피치에 더합니다. 마우스를 위로 움직이면 음수인  `delta.y` 값이 보고되어 피치가 낮아지고 카메라가 위로 기울어집니다. 수직 조작을 반대로 하려면 부호를 바꾸세요.
* 피치는 -85도에서 85도 사이로 제한되어 카메라가 뒤로 뒤집히지 않습니다.
* 상수  `SENSITIVITY` 는 마우스 이동 픽셀당 회전 각도를 나타냅니다. 원하는 대로 조정하세요.

{% hint style="info" %}
**💡 팁**: 플레이어는 언제든지  *Esc* 를 누르거나 마우스 오른쪽 버튼을 클릭하여 커서 잠금을 해제할 수 있으며, 그러면 카메라가 마우스에 반응하지 않습니다. 위 예제의 보조 버튼처럼 플레이어가 카메라 모드를 완전히 종료할 수 있는 명확한 방법을 항상 제공하세요. 코드에서 커서를 다시 잠글 수도 있습니다. 다음을 참조하세요:  [커서 잠금 또는 잠금 해제](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/button-events/click-events.md#lock-or-unlock-the-cursor).
{% endhint %}

## 관련 항목

커서의 움직임 대신 화면상의 절대 위치를 읽으려면 같은 컴포넌트의  `screenCoordinates`  속성을 사용하세요. 다음을 참조하세요:  [플레이어의 커서 위치 확인](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/user-data.md#check-the-players-cursor-position).

커서 아래에 있는 엔티티를 알아내려면 다음을 조합하세요:  `worldRayDirection` 레이캐스트에 사용할 속성입니다. 자세한 내용은 [레이캐스팅](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/raycasting.md).

{% hint style="info" %}
**💡 팁**: 포인터 상태의 작동 예시는 다음을 참조하세요. [`0,5-primary-cursor-info`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/0,5-primary-cursor-info) 테스트 씬에서는 매 프레임 `PrimaryPointerInfo` 를 읽고 `worldRayDirection` 을 레이캐스트에 전달합니다. [`31,20-pointer-lock-control`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/31,20-pointer-lock-control)에서는 다음 값을 기록해 커서 캡처를 요청하고 해제합니다. `PointerLock.isPointerLocked`그리고 [`32,20-virtual-camera-mouse-look`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/32,20-virtual-camera-mouse-look)에서는 `screenDelta` 가 계속 움직임을 보고하는 동안 `screenCoordinates` 는 포인터 잠금 중 화면 중앙에 고정되는 모습을 보여 줍니다.
{% 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/interactivity/mouse-movement.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.
