> 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/user-data.md).

# 사용자 데이터

플레이어가 씬과 상호작용할 때 데이터를 가져오세요.

## 플레이어 위치 및 회전

플레이어의 위치와 회전을 확인하려면 `PlayerEntity` 와 `CameraEntity` 의 `Transform` 컴포넌트를 확인하세요.

```ts
function getPlayerPosition() {
	if (!Transform.has(engine.PlayerEntity)) return
	if (!Transform.has(engine.CameraEntity)) return

	//플레이어 위치
	const playerPos = Transform.get(engine.PlayerEntity).position

	//플레이어 회전
	const playerRot = Transform.get(engine.PlayerEntity).rotation

	//카메라 위치
	const CameraPos = Transform.get(engine.CameraEntity).position

	//카메라 회전
	const CameraRot = Transform.get(engine.CameraEntity).rotation

	console.log('playerPos: ', playerPos)
	console.log('playerRot: ', playerRot)
	console.log('cameraPos: ', CameraPos)
	console.log('cameraRot: ', CameraRot)
}

engine.addSystem(getPlayerPosition)
```

* **PlayerEntity 위치**: 아바타의 위치로, 가슴 높이에 있습니다. 지면에서 약 0.88미터 위입니다.
* **PlayerEntity 회전**: 아바타가 향하는 방향을 쿼터니언으로 나타냅니다.
* **CameraEntity 위치**:
  * 1인칭 시점: 아바타의 위치와 같지만 눈높이에 있습니다. 지면에서 약 1.75미터 위입니다.
  * 3인칭 시점: 카메라 움직임에 따라 달라질 수 있습니다.
* **PlayerEntity 회전**:
  * 1인칭 시점: 아바타가 향하는 방향과 비슷하며 쿼터니언으로 나타냅니다. 플레이어의 회전과 약간 다르게 반올림될 수 있습니다.
  * 3인칭 시점: 카메라 움직임에 따라 달라질 수 있습니다.

{% hint style="warning" %}
**📔 참고**초기 씬 로드 시 `engine.PlayerEntity` 또는 `engine.CameraEntity` 를 참조하지 마세요. 엔티티가 아직 초기화되지 않았다면 오류가 발생할 수 있습니다. 이 문제를 방지하려면 이를 `main()` 함수 내부나 이 함수에서 간접적으로 호출되는 함수 내부에서 사용하세요 `main()`. 또는 비동기 [`executeTask` 블록으로 동작을 감쌀 수도 있습니다.](https://docs.decentraland.org/creator/content-creator-ko/sdk7/programming-patterns/async-functions.md#the-executetask-function).

또 다른 방법은 시스템 내부에서 이러한 엔티티를 참조하는 것입니다. 시스템의 첫 실행은 씬이 완전히 초기화된 뒤에 이루어지므로, 시스템 안에서는 항상 이러한 엔티티를 사용할 수 있습니다.
{% endhint %}

## 모든 플레이어 가져오기

씬의 모든 플레이어에는 `Transform` 컴포넌트가 있습니다. 아바타에서는 이 컴포넌트를 읽기만 할 수 있습니다. 모든 플레이어의 위치를 가져오려면 [다음이 있는 모든 엔티티를 순회하세요](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/user-data.md) a `PlayerIdentityData` 컴포넌트입니다.

```ts
import { PlayerIdentityData } from '@dcl/sdk/ecs'

for (const [entity, data, transform] of engine.getEntitiesWith(
	PlayerIdentityData,
	Transform
)) {
	console.log('Player data: ', { entity, data, transform })
}
```

위 코드는 `Transform` 및 `PlayerIdentityData` 컴포넌트가 있는 모든 엔티티를 순회하며 데이터를 기록합니다. 이 방법을 사용하면 모든 플레이어의 사용 가능한 데이터를 가져올 수 있습니다.

새 플레이어가 씬에 들어올 때 이를 감지하고 대응하는 방법은 [이벤트 리스너](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/event-listeners.md#player-enters-or-leaves-scene) 를 참조하세요.

## 플레이어 데이터 가져오기

현재 플레이어나 씬에 있는 다른 플레이어의 데이터를 가져오려면 `getPlayer()` 를 사용하세요.

```ts
import { getPlayer } from '@dcl/sdk/src/players'

export function main() {
	createCube(5, 1, 5)

	let myPlayer = getPlayer()

	if (myPlayer) {
		console.log('Name : ', myPlayer.name)
		console.log('UserId : ', myPlayer.userId)
	}
}
```

`getPlayer()` 는 다음을 반환합니다.

* `name`: *(문자열)* 게임 내에서 다른 플레이어에게 표시되는 플레이어의 사용자 이름
* `userId`: *(문자열)* 플레이어를 식별하는 문자열입니다. 지갑으로 연결한 플레이어의 경우 소문자로 표기된 지갑 주소입니다. 게스트 계정의 경우 로컬에서 생성된 식별자입니다.
* `isGuest`: *(불리언)* 플레이어에게 공개 키가 있는지 나타냅니다. *공개 키가 없는 게스트 계정인 경우* 값은 true입니다.
* `position`: *(Vector3)* 씬에서 아바타의 위치입니다.
* `avatar`: 플레이어의 기본 아바타와 외형에 관한 데이터가 포함된 중첩 객체입니다.
* `wearables`: 플레이어가 현재 착용 중인 웨어러블 각각의 식별자 배열입니다. 예를 들면 `urn:decentraland:off-chain:base-avatars:green_hoodie`입니다. NFT를 포함해 모든 웨어러블은 이와 비슷한 식별자를 사용합니다.
* `emotes`: 플레이어가 현재 빠른 실행 휠에 장착한 이모트 각각의 식별자 배열입니다.
* `entity`: 플레이어 엔티티에 대한 참조입니다. 다른 함수에 전달하거나 사용자 지정 컴포넌트를 추가할 때 유용합니다.

이 `avatar` 객체에는 다음과 같은 중첩 정보가 있습니다.

* `bodyShapeUrn`: 아바타의 전체적인 체형을 나타내는 식별자입니다. 여성인 경우 `urn:decentraland:off-chain:base-avatars:BaseFemale` , 남성인 경우 `urn:decentraland:off-chain:base-avatars:BaseMale` 입니다.
* `skinColor`: 플레이어의 피부색을 나타내는 `Color3`
* `eyesColor`: 플레이어의 눈 색깔을 나타내는 `Color3`
* `hairColor`: 플레이어의 머리카락 색깔을 나타내는 `Color3`
* `name`: 플레이어의 이름입니다.

{% hint style="warning" %}
**📔 참고**: 로드 시간에 따라 씬의 첫 번째 프레임에서 플레이어 데이터를 사용하지 못할 수 있습니다. 데이터가 반환되었는지 확인하고, 반환되지 않았다면 몇 밀리초 후에 다시 시도해야 합니다.
{% endhint %}

```ts
import { getPlayer } from '@dcl/sdk/src/players'

export function main() {
	createCube(5, 1, 5)

	let myPlayer = getPlayer()

	if (myPlayer) {
		console.log('Is Guest: ', myPlayer.isGuest)
		console.log('Name : ', myPlayer.name)
		console.log('UserId : ', myPlayer.userId)
		console.log('Avatar shape : ', myPlayer.position)
		console.log('Avatar shape : ', myPlayer.avatar?.bodyShapeUrn)
		console.log('Avatar eyes color : ', myPlayer.avatar?.eyesColor)
		console.log('Avatar hair color : ', myPlayer.avatar?.hairColor)
		console.log('Wearables on : ', myPlayer.wearables)
		console.log('Emotes available : ', myPlayer.emotes)
	}
}
```

현재 플레이어가 아닌 씬의 특정 플레이어 데이터를 가져오려면 `getPlayer()` 에 `userId` 속성이 있는 객체를 전달하여 실행합니다.

```ts
import { getPlayer } from '@dcl/sdk/src/players'

for (const [entity, data, transform] of engine.getEntitiesWith(
	PlayerIdentityData,
	Transform
)) {
	let player = getPlayer({ userId: data.address })
	console.log('PLAYER : ', player?.name)
}
```

위 코드는 `PlayerIdentityData` 컴포넌트가 있는 모든 엔티티, 즉 씬의 모든 아바타 엔티티를 순회합니다. 그런 다음 해당 엔티티에 대해 `getPlayer()` 를 실행합니다.

`getPlayer()` 는 현재 같은 씬에 있는 플레이어의 데이터만 가져올 수 있습니다. 플레이어가 반드시 시야 범위 안에 있어야 하는 것은 아니지만, 같은 통신 아일랜드에 연결되어 있어야 합니다. 미리보기에서 이를 시험하려면 두 번째 탭을 열고 다른 계정으로 로그인한 다음, 두 플레이어를 모두 씬 안에 배치하세요.

{% hint style="warning" %}
**📔 참고**: 사용자 ID는 항상 소문자여야 합니다. 지갑 주소를 복사할 때는 모든 문자가 소문자인지 확인하세요.
{% endhint %}

## 모든 플레이어의 데이터

모든 플레이어의 정보를 가져오려면 [REST API 호출](https://docs.decentraland.org/creator/content-creator-ko/sdk7/networking/network-connections.md#call-a-rest-api) 을 콘텐츠 서버에 수행합니다.

이 정보는 플레이어의 사용자 ID를 URL 매개변수에 추가한 다음 URL에서 확인할 수 있습니다.

`https://peer.decentraland.org/lambdas/profile/<player user id>`

{% hint style="info" %}
**💡 팁**: 브라우저에서 URL을 열어 응답 구조를 확인해 보세요.
{% endhint %}

이 API에서 다음 정보를 확인할 수 있습니다.

* `displayName`: *(문자열)* 게임 내에서 다른 플레이어에게 표시되는 플레이어의 사용자 이름
* `userId`: *(문자열)* 플레이어를 식별하는 UUID 문자열입니다. 플레이어에게 공개 키가 있으면 이 필드의 값은 공개 키와 같습니다.
* `hasConnectedWeb3`: *(불리언)* 플레이어에게 공개 키가 있는지 나타냅니다. *플레이어에게 공개 키가 있으면* 참입니다.
* `publicKey`: *(문자열)* 플레이어의 이더리움 지갑 공개 키입니다. 연결된 지갑 없이 게스트로 로그인한 경우 이 필드는 `null`.
* `avatar`: 플레이어의 외형에 관한 데이터가 포함된 중첩 객체입니다.
* `version`: *(숫자)* 플레이어가 설정을 변경할 때마다 1씩 증가하는 버전 번호입니다. 데이터가 충돌하는 경우 이 값을 사용해 어느 버전이 더 최신인지 확인하세요.

{% hint style="warning" %}
**📔 참고**: 플레이어와 관련된 이더리움 트랜잭션에서는 존재하지 않는 지갑을 처리하지 않도록 항상 `publicKey` 필드를 사용하고, `userId`는 사용하지 마세요.
{% endhint %}

이 `avatar` 객체에는 다음과 같은 중첩 정보가 있습니다.

* `wearables`: `WearableId[]` 플레이어가 현재 착용 중인 각 웨어러블의 식별자 배열입니다. 예를 들면 `urn:decentraland:off-chain:base-avatars:green_hoodie`입니다. NFT를 포함해 모든 웨어러블은 비슷한 식별자를 사용합니다.
* `bodyShape`: 아바타의 전반적인 체형을 식별하는 값입니다. 다음 중 하나입니다. `urn:decentraland:off-chain:base-avatars:BaseFemale` 여성형 또는 `urn:decentraland:off-chain:base-avatars:BaseMale` 남성형입니다.
* `skin`: 다음 항목이 포함된 객체입니다. `color` 플레이어의 피부색을 나타내는 `{ r, g, b, a }` 0부터 1까지의 숫자로 구성된 필드입니다.
* `hair`: 다음 항목이 포함된 객체입니다. `color` 필드로, 플레이어의 머리카락 색상을 다음 형식으로 저장합니다. `{ r, g, b, a }` 0부터 1까지의 숫자입니다.
* `eyes`: 다음 항목을 포함하는 객체입니다. `color` 필드로, 플레이어의 눈 색상을 다음 형식으로 저장합니다. `{ r, g, b, a }` 0부터 1까지의 숫자입니다.
* `snapshots`: 다양한 해상도의 플레이어 이미지(.jpg)를 base64로 표현한 중첩 객체입니다.
  * `face256`: *문자열* 256x256픽셀 이미지로 표현한 플레이어의 얼굴입니다.
  * `body`: *문자열* 똑바로 서 있는 플레이어의 512x1024픽셀 전체 해상도 이미지입니다.

{% hint style="danger" %}
**❗경고** 아바타 스냅샷은 향후 지원 중단되어 아바타 데이터에 더 이상 포함되지 않습니다. 대신 다음을 사용하는 방법을 권장합니다. `AvatarTexture` 자세한 내용은 다음을 참조하세요. [아바타 초상화](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/materials.md#avatar-portraits).
{% endhint %}

getPlayer() `와 달리`이 옵션은 현재 같은 씬이나 같은 서버에 있는 플레이어로 제한되지 않습니다. 이 방법을 사용하면 과거에 서버에 로그인한 적이 있는 모든 플레이어의 데이터를 가져올 수 있습니다.

조회하려는 플레이어가 연결된 서버를 알고 있다면, 해당 서버로 요청을 보내 더 최신 데이터를 가져올 수 있습니다. 예를 들어 플레이어가 옷을 바꾸면 이 정보는 플레이어의 서버에 즉시 반영되지만, peer.decentraland.org 서버로 전파되기까지는 몇 분 정도 걸릴 수 있습니다. `peer.decentraland.org` 서버에 반영되기까지는 몇 분 정도 걸릴 수 있습니다.

`https://<player server>/lambdas/profile/<player user id>`

{% hint style="info" %}
**💡 팁**: 현재 플레이어의 서버는 다음을 호출해 가져올 수 있습니다. `getRealm()` 그런 다음 응답의 `realmInfo.baseUrl` 필드를 읽으세요.
{% endhint %}

이 예제에서는 `myProfile.userId` 와 `getRealm()` 을 결합해 플레이어가 접속 중인 서버에서 직접 플레이어 데이터를 가져옵니다.

```ts
import { getRealm } from '~system/Runtime'
import { myProfile } from '@dcl/sdk/network'

async function fetchPlayerData() {
	const { realmInfo } = await getRealm({})
	if (!realmInfo) return

	const url = `${realmInfo.baseUrl}/lambdas/profile/${myProfile.userId}`
	console.log('using URL: ', url)

	try {
		const response = await fetch(url)
		const json = await response.json()

		console.log('full response: ', json)
		console.log('player is wearing :', json.avatars[0].avatar.wearables)
	} catch {
		console.log('an error occurred while reaching for player data')
	}
}

fetchPlayerData()
```

## 플레이어 데이터 구성 요소

를 사용하는 대신 `getPlayer()`, 각 플레이어 엔티티에 데이터를 저장하는 일련의 구성 요소에서 데이터를 직접 읽을 수 있습니다. 다음 구성 요소를 사용할 수 있습니다:

* `PlayerIdentityData`: 플레이어 주소와 게스트 계정을 표시하는 `isGuest` 속성을 저장합니다.
* `AvatarBase`: 기본 아바타에 관한 데이터를 저장하며, 다음을 포함합니다:
  * `name`: 플레이어의 이름입니다.
  * `bodyShapeUrn`: 남성 또는 여성 체형에 해당하는 ID입니다.
  * `skinColor`: 플레이어의 피부색을 나타내는 `Color3`
  * `eyesColor`: 플레이어의 눈 색깔을 나타내는 `Color3`
  * `hairColor`: 플레이어의 머리카락 색깔을 나타내는 `Color3`
  * `talking`: *true* 는 플레이어가 음성 채팅으로 말하는 동안, *false* 는 플레이어가 조용할 때, *undefined* 는 클라이언트가 해당 플레이어의 음성 활동이 없다고 보고할 때의 값입니다. 자세한 내용은 [플레이어가 말하는 시점 감지](#detect-when-a-player-is-speaking).
* `AvatarEquippedData`: 장착한 웨어러블과 이모트 목록입니다.
  * `wearableUrns`: 플레이어가 현재 장착한 웨어러블 목록입니다.
  * `emoteUrns`: 플레이어가 빠른 액세스 휠에 현재 장착한 이모트 목록입니다.
* `AvatarEmoteCommand`: 플레이어가 현재 재생 중인 이모트에 관한 정보입니다. 다음 항목을 포함합니다:
  * `emoteUrn`: 플레이어가 씬에 들어온 이후 마지막으로 재생한 이모트의 URN입니다.
  * `loop`: 이모트가 반복 재생 중이면 True입니다.
  * `timestamp`: 이 이모트가 실행된 시각입니다.

```ts
for (const [entity, data, base, attach, transform] of engine.getEntitiesWith(
	PlayerIdentityData,
	AvatarBase,
	AvatarEquippedData,
	Transform
)) {
	console.log('PLAYER DATA: ', { entity, data, transform, base, attach })
}
```

{% hint style="warning" %}
**📔 참고**: 이러한 구성 요소는 모두 읽기 전용입니다. 씬에서 값을 변경할 수 없습니다.
{% endhint %}

## 플레이어가 말하는 시점 감지

다음에서 `talking` 을 읽습니다 `AvatarBase` 는 현재 음성 채팅에서 누군가 말하고 있는지 확인하는 컴포넌트입니다. 씬을 실행하는 플레이어와 주변의 다른 모든 플레이어에 대해 작동합니다.

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

// 로컬 플레이어가 말하기를 시작하거나 멈출 때마다 기록
AvatarBase.onChange(engine.PlayerEntity, (base) => {
	console.log('talking: ', base?.talking)
})
```

`talking` 에는 두 가지가 아닌 세 가지 상태가 있습니다.

| 값           | 의미                                                              |
| ----------- | --------------------------------------------------------------- |
| `true`      | 플레이어가 현재 말하고 있습니다.                                              |
| `false`     | 플레이어가 말하고 있지 않습니다.                                              |
| `undefined` | 예를 들어 주변 음성 채팅이 꺼져 있는 경우처럼, 클라이언트가 이 플레이어의 음성 활동을 보고하지 않고 있습니다. |

세 번째 상태도 중요합니다. `undefined` 는 "데이터 없음"을 뜻하며 "조용함"을 뜻하지 않습니다. 이를 명시적으로 확인하고, true가 아닌 모든 값을 조용한 상태로 간주하지 마세요.`true` 값을 조용한 상태로 간주하지 마세요.

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

function whoIsSpeaking() {
	for (const [player, base] of engine.getEntitiesWith(AvatarBase)) {
		if (base.talking === undefined) continue // 이 플레이어의 음성 데이터 없음
		if (base.talking) console.log(`${base.name} is speaking`)
	}
}

engine.addSystem(whoIsSpeaking)
```

말하고 있는 플레이어의 머리 위에 마커를 표시하려면 다음을 사용해 마커를 연결하세요. [`AvatarAttach`](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/entity-positioning.md#attach-to-other-players) 다음에서 가져온 주소를 사용합니다. `PlayerIdentityData`. 플레이어의 엔티티를 마커의 부모로 지정하지 마세요. 제대로 작동하지 않으며 마커가 씬 원점에 표시됩니다.

{% hint style="warning" %}
**📔 참고**: `AvatarBase.talking` 은 실제 음성 채팅 활동을 보고하며, 여기에 값을 쓸 수 없습니다. 다음과는 다른 기능입니다. `AvatarShape.talking`. 이는 씬에서 설정하는 플래그로, 생성한 [NPC 아바타](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/avatars/npc-avatars.md) 옆에 녹색 음성 막대를 표시합니다.
{% endhint %}

## 포터블 경험 가져오기

포터블 경험은 기본적으로 토지 구획에 제한되지 않는 씬입니다. 플레이어는 Decentraland 어디든 이동할 때 이를 가지고 다니며, 월드에 새로운 콘텐츠 레이어를 추가할 수 있습니다. 스마트 웨어러블은 포터블 경험의 한 예입니다. 스마트 웨어러블을 착용하면 경쟁 게임에서 부정행위로 간주될 수 있는 능력을 플레이어에게 부여할 수도 있으므로, 플레이어가 이를 착용하고 있는지 확인해야 할 수 있습니다. 예를 들어 플랫폼 게임에서 제트팩을 착용한 플레이어는 다른 플레이어보다 매우 불공정한 이점을 갖습니다.

씬 제작자는 포터블 경험을 착용한 플레이어가 씬에서 할 수 있는 행동을 제한하고 싶을 수 있습니다. 다음을 사용하세요. `getPortableExperiencesLoaded()` 플레이어가 현재 활성화한 포터블 경험이 있는지 확인합니다.

```ts
import { getPortableExperiencesLoaded } from '~system/PortableExperiences'

executeTask(async () => {
	let portableExperiences = await getPortableExperiencesLoaded({})
	console.log(portableExperiences.loaded)
})
```

`getPortableExperiencesLoaded()` 는 객체 배열을 반환하며, 각 객체에는 다음 속성이 포함됩니다. `id` 웨어러블의 경우 이 id는 웨어러블의 URN입니다.

## 플레이어의 웨어러블에 대한 상세 정보 가져오기

다음 `getPlayer()` 함수는 각 웨어러블에 대한 정보 없이 웨어러블 ID 목록만 반환합니다. 특정 카테고리(예: 모자)나 특정 희귀도(예: Mythic)의 웨어러블이 있는지 확인하려면 플레이어의 웨어러블에 대한 더 자세한 정보를 가져와야 합니다.

다음 URL로 [REST API 호출](https://docs.decentraland.org/creator/content-creator-ko/sdk7/networking/network-connections.md#call-a-rest-api) 을 보내면 현재 사용할 수 있는 모든 웨어러블의 최신 목록과 각 웨어러블의 상세 정보를 가져올 수 있습니다.

`${playerRealm.realmInfo.baseUrl}/lambdas/collections/wearables-by-owner/${userData.userId}?includeDefinitions`

{% hint style="warning" %}
**📔 참고**: 이 URL을 구성하려면 렐름(일반적으로 `getRealm()`사용)과 플레이어 ID(일반적으로 `getPlayer()`)
{% endhint %}

이 기능을 플레이어 정보 조회와 함께 사용하면, 예를 들어 플레이어가 할로윈 컬렉션의 웨어러블이나 *전설* 희귀도의 웨어러블을 착용한 경우에만 특정 장소에 입장하도록 허용할 수 있습니다.

{% hint style="info" %}
**💡 팁**: 브라우저에서 URL을 열어 응답 구조를 확인해 보세요.
{% endhint %}

```ts
import { getPlayer } from '@dcl/sdk/src/players'
import { getRealm } from '~system/Runtime'

async function fetchWearablesData() {
	try {
		let userData = getPlayer()
		const realm = await getRealm({})
		if (!userData || !realm.realmInfo) return

		const url =
			`${realm.realmInfo?.baseUrl}/lambdas/collections/wearables-by-owner/${userData.userId}?includeDefinitions`.toString()
		console.log('using URL: ', url)

		let response = await fetch(url)
		let json = await response.json()

		console.log('full response: ', json)
	} catch {
		console.log('an error occurred while reaching for wearables data')
	}
}

executeTask(fetchWearablesData)
```

{% hint style="info" %}
**💡 팁**: 특정 웨어러블에 대한 더 자세한 정보는 [다음 API에서 가져올 수 있습니다](https://decentraland.github.io/catalyst-api-specs/#tag/Lambdas/operation/searchWearables).
{% endhint %}

## 플레이어의 카메라 모드 확인하기

플레이어는 Decentraland를 탐험할 때 1인칭 또는 3인칭 카메라를 사용할 수 있습니다. 플레이어가 어느 모드를 사용 중인지 확인하려면 `CameraMode` 컴포넌트의 값을 확인하세요. 이 컴포넌트는 `engine.CameraEntity` 엔티티에 있습니다.

```ts
function checkCameraMode() {
	if (!CameraMode.has(engine.CameraEntity)) return

	let cameraEntity = CameraMode.get(engine.CameraEntity)

	if (cameraEntity.mode == CameraType.CT_THIRD_PERSON) {
		console.log('The player is using the 3rd person camera')
	} else {
		console.log('The player is using the 1st person camera')
	}
}

engine.addSystem(checkCameraMode)
```

{% hint style="warning" %}
**📔 참고**: 카메라 정보는 씬을 실행 중인 현재 플레이어에 대해서만 사용할 수 있습니다. 다른 플레이어의 카메라 데이터는 조회할 수 없습니다.
{% endhint %}

카메라 모드는 `CameraType` 열거형의 값을 사용합니다. 가능한 값은 다음과 같습니다.

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

다음 `CameraMode` 컴포넌트는 `engine.CameraEntity` 의 읽기 전용 컴포넌트이므로 이를 통해 플레이어의 카메라 모드를 강제로 변경할 수 없습니다.

{% hint style="info" %}
**💡 팁**: 플레이어의 카메라 모드를 변경하려면 다음을 사용하세요. [카메라 수정자 영역](https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/camera.md#1st-and-3rd-person-camera-modes).
{% endhint %}

카메라 모드를 알면 이 모드에서 더 편하게 사용할 수 있도록 장면의 메커니즘을 세밀하게 조정하는 데 매우 유용합니다. 예를 들어 3인칭 모드에서는 작은 대상을 클릭하기가 더 어렵습니다.

{% hint style="warning" %}
**📔 참고**: 초기 장면 로드 시에는 `engine.CameraEntity` 를 참조하지 마세요. 엔터티가 아직 초기화되지 않은 경우 오류가 발생할 수 있습니다. 이 문제를 방지하려면 다음을 `main()` 함수 또는 `main()`에서 간접적으로 호출되는 함수 안에서 사용하세요. 동작을 비동기 [`executeTask` 블록으로 감쌀 수도 있습니다.](https://docs.decentraland.org/creator/content-creator-ko/sdk7/programming-patterns/async-functions.md#the-executetask-function).

또 다른 방법은 시스템 안에서 이 엔터티를 참조하는 것입니다. 시스템의 첫 실행은 장면이 제대로 초기화된 후에 호출되므로 항상 사용할 수 있습니다.
{% endhint %}

## 플레이어의 커서가 잠겨 있는지 확인하기

플레이어는 다음 두 가지 커서 모드 사이를 전환할 수 있습니다. *커서 잠금* 모드는 카메라를 조작하고, *커서 잠금 해제* 모드는 UI 위에서 커서를 자유롭게 움직입니다.

플레이어는 *마우스 오른쪽 버튼* 을 클릭하거나 *Esc* 키를 눌러 커서 잠금을 해제하고, 화면의 아무 곳이나 클릭해 다시 잠급니다.

장면의 `PointerLock` 컴포넌트를 확인하여 [카메라 엔터티](https://docs.decentraland.org/creator/content-creator-ko/sdk7/architecture/entities-components.md#reserved-entities) 의 현재 커서 모드를 알아보세요.

```ts
export function main() {
	const isLocked = PointerLock.get(engine.CameraEntity).isPointerLocked
	console.log(isLocked)
}
```

커서 상태 변화에 간편하게 반응하는 방법은 [이벤트 리스너](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/event-listeners.md#player-locks-or-unlocks-cursor) 를 참조하세요.

플레이어의 커서 상태를 강제로 변경하려면 `isPointerLocked` 필드에 값을 쓰면 됩니다. 이 필드는 `PointerLock` 컴포넌트의 `engine.CameraEntity`에 있습니다. 예제는 [커서 잠금 또는 잠금 해제](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/button-events/click-events.md#lock-or-unlock-the-cursor) 를 참조하세요.

{% hint style="warning" %}
**📔 참고**: 초기 장면 로드 시에는 `engine.CameraEntity` 를 참조하지 마세요. 엔터티가 아직 초기화되지 않은 경우 오류가 발생할 수 있습니다. 이 문제를 방지하려면 다음을 `main()` 함수 또는 `main()`에서 간접적으로 호출되는 함수 안에서 사용하세요. 동작을 비동기 [`executeTask` 블록으로 감쌀 수도 있습니다.](https://docs.decentraland.org/creator/content-creator-ko/sdk7/programming-patterns/async-functions.md#the-executetask-function).

또 다른 방법은 시스템 안에서 엔터티를 참조하는 것입니다. 시스템의 첫 실행은 장면이 제대로 초기화된 후에 호출되므로 항상 사용할 수 있습니다.
{% endhint %}

## 플레이어의 커서 위치 확인하기

플레이어의 커서 위치를 가져오려면 `PrimaryPointerInfo` 컴포넌트를 `engine.RootEntity` 에서 사용하세요. 드래그 앤 드롭 상호작용이나 스와이프 제스처 등의 메커니즘에 활용할 수 있습니다.

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

function CursorSystem() {
	const pointerInfo = PrimaryPointerInfo.get(engine.RootEntity)
	console.log(pointerInfo)
}

engine.addSystem(CursorSystem)
```

{% hint style="warning" %}
**📔 참고**를 참조하지 마세요. `engine.RootEntity` 를 참조하지 마세요. 씬이 처음 로드될 때 엔티티가 아직 초기화되지 않았다면 오류가 발생할 수 있습니다. 이 문제를 방지하려면 항상 시스템 내부에서 엔티티를 참조하세요. 시스템의 첫 실행은 씬이 완전히 초기화된 후에 이루어지므로 엔티티를 항상 사용할 수 있습니다.
{% endhint %}

The `PrimaryPointerInfo` 컴포넌트는 다음 속성을 가진 객체를 반환합니다:

* `screenCoordinates`: *(Vector2)* 씬에서 커서의 위치를 픽셀 단위로 나타냅니다. 원점은 화면의 왼쪽 위 모서리이며, `y` 축은 아래쪽으로 증가합니다. 이는 다음과 동일한 좌표 공간입니다. `UiTransform` 및 `UiCanvasInformation`커서가 잠겨 있으면 화면의 중앙을 반환합니다.
* `screenDelta`: *(Vector2)* 마지막 프레임 이후 커서 위치의 변화량을 픽셀 단위로 나타냅니다. 자세한 내용과 예시는 다음을 참조하세요. [마우스 움직임](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/mouse-movement.md) 에서 확인할 수 있습니다.
* `worldRayDirection`: *(Vector3)* 카메라에서 커서로 향하는 광선의 방향을 나타내는 벡터입니다. 원점은 카메라 위치입니다. 이 값을 사용해 월드에서 커서의 위치를 계산할 수 있습니다.
* `pointerType`: 0은 `none`, 1은 `mouse`

{% hint style="info" %}
**💡 팁**: 다른 속성과 달리, `screenDelta` 는 커서가 [잠겨 있는 동안에도 마우스 움직임을 계속 보고합니다](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/button-events/click-events.md#lock-or-unlock-the-cursor). 따라서 드래그 동작이나 사용자 지정 카메라 제어와 같은 실시간 상호작용에 적합합니다. 자세한 내용은 다음을 참조하세요 [마우스 이동](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/mouse-movement.md).
{% endhint %}

{% hint style="info" %}
**팁:** UI 요소의 간단한 마우스 오버 이벤트에 반응하려면 다음을 사용하는 것이 더 쉬울 수 있습니다. `onMouseEnter` 및 `onMouseLeave` 이벤트를 참고하세요. [UI 버튼 이벤트](https://docs.decentraland.org/creator/content-creator-ko/sdk7/2d-ui/ui_button_events.md#hover-feedback).
{% endhint %}

다음 `PrimaryPointerInfo` 구성 요소는 읽기 전용이므로 플레이어가 커서 위치를 변경하도록 강제할 수 없습니다.

다음 예제에서는 UI 요소에 커서 위치를 표시하는 방법을 보여 줍니다.

***ui.tsx 파일:***

```tsx
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'
import {cursorXpos, cursorYpos} from './index'

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
			width: '100%',
			height: '100px',
			justifyContent: 'center',
			alignItems: 'center',
    }}
    uiText={{ value: `Cursor pos: `+  cursorXpos + `,` + cursorYpos, fontSize: 40 }}
    uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
  />
)
```

***index.ts 파일:***

```ts
import { engine, PrimaryPointerInfo } from '@dcl/sdk/ecs'
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
  ReactEcsRenderer.setUiRenderer(uiMenu)
}

export let cursorXpos: number | undefined = undefined
export let cursorYpos: number | undefined = undefined

function CursorSystem() {
  const pointerInfo = PrimaryPointerInfo.get(engine.RootEntity)
  console.log(pointerInfo)

  cursorXpos = pointerInfo.screenCoordinates?.x
  cursorYpos = pointerInfo.screenCoordinates?.y
}

engine.addSystem(CursorSystem)
```

다음을 사용해 `worldRayDirection` 레이캐스트의 `direction` 필드를 설정하면 엔티티가 커서의 시야선상에 있는지 확인할 수 있습니다. 자세한 내용은 [레이캐스팅](https://docs.decentraland.org/creator/content-creator-ko/sdk7/interactivity/raycasting.md) 을 참조하세요.


---

# 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/user-data.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.
