> 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/2d-ui/ui_button_events.md).

# UI 버튼 이벤트

UI 엔티티의 버튼 이벤트를 처리합니다.

UI에 버튼을 만들려면 다음 속성을 가진 `Button` UI 요소를 생성합니다.

* `value`: 버튼에 표시할 텍스트 문자열입니다.
* `onMouseDown`: 사용자가 엔티티에서 포인터 버튼을 누를 때마다 실행되는 콜백 함수입니다.
* `uiTransform`: UI 요소의 위치 지정 속성입니다.

다음 예제는 클릭 가능한 UI 버튼을 만드는 방법을 보여 줍니다.

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

```tsx
import { Button } from '@dcl/sdk/react-ecs'

export const uiMenu = () => (
	<Button
		value="Click me"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			console.log('Clicked on the UI')
		}}
	/>
)
```

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

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

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

{% hint style="warning" %}
**📔 참고**: 이 페이지의 다음 모든 코드 조각은 다음과 같은 `.ts` 파일에서 위와 비슷하게 `ReactEcsRenderer.setUiRenderer()` 함수를 실행한다고 가정합니다.
{% endhint %}

클릭 시 실행되는 함수를 UI 정의 바깥에 작성하고 이름으로 참조할 수도 있습니다. 이렇게 하면 UI 코드를 더 읽기 쉽게 유지할 수 있으며, 클릭 가능한 UI 엔티티 여러 개에서 같은 함수를 호출해야 할 때도 유용합니다.

```tsx
import { Button } from '@dcl/sdk/react-ecs'

function handleClick() {
	// Do something onClick
	console.log('Clicked on the UI')
}
export const uiMenu = () => (
	<Button
		value="Click me"
		uiTransform={{ width: 100 }}
		onMouseDown={handleClick}
	/>
)
```

다음 필드를 `Button` UI 요소에 추가할 수 있습니다:

* `onMouseDown`: 사용자가 엔티티에서 포인터 버튼을 누를 때마다 실행되는 콜백 함수입니다.
* `onMouseUp`: 엔티티를 가리키는 동안 포인터 버튼을 놓을 때마다 실행되는 콜백 함수입니다.
* `onMouseEnter`: 포인터가 버튼 위에 올라올 때마다 실행되는 콜백 함수입니다.
* `onMouseLeave`: 포인터가 버튼 위에서 벗어날 때마다 실행되는 콜백 함수입니다.
* `color`: 버튼 텍스트의 색상입니다.
* `font`: 버튼 텍스트의 글꼴입니다.
* `textAlign`: 버튼 내부 텍스트의 정렬 방식입니다.
* `uiTransform`: UI 요소의 위치 지정 속성입니다.
* `uiBackground`: UI 요소의 색상이나 텍스처를 설정합니다.
* `variant`: 이 속성을 사용해 버튼 스타일을 기본 옵션 중 하나로 설정합니다. `primary` 및 `secondary` 를 사용할 수 있습니다.
* `disabled`: 버튼을 비활성화하는 불리언 값입니다. `disabled` 이 *true*로 설정되면, `onMouseDown` 및 `onMouseUp` 동작은 더 이상 호출되지 않으며, 버튼이 포인터 상호작용을 표시하지 않습니다. 버튼도 "회색으로 흐리게" 표시됩니다. 텍스트와 배경 모두 해당 `alpha` 값의 절반으로 렌더링됩니다. 이는 표시만 변경합니다. `Color4` 장면에서 전달하는 값은 수정되지 않으므로, 여러 요소에서 공유 팔레트 객체를 안전하게 재사용할 수 있습니다.

## 버튼 스타일 지정

버튼의 기본 스타일 옵션을 활용하려면 variant를 `primary` 또는 `secondary` 로 설정합니다. `primary` 는 버튼을 흰색 텍스트가 있는 빨간색으로 표시하고, `secondary` 는 버튼을 빨간색 텍스트가 있는 흰색으로 표시합니다.

```tsx
import { UiEntity, Button, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
	<UiEntity
		uiTransform={{
			width: 500,
			height: 230,
			margin: '16px 0 8px 270px',
			padding: 4,
			alignSelf: 'center',
		}}
		uiBackground={{ color: Color4.Gray() }}
	>
		<Button
			value="Click Me"
			variant="primary"
			uiTransform={{ width: 80, height: 20, margin: 4 }}
			onMouseDown={() => {
				console.log('Clicked on the UI')
			}}
		/>
		<Button
			value="Click Me"
			variant="secondary"
			uiTransform={{ width: 80, height: 20, margin: 4 }}
			onMouseDown={() => {
				console.log('Clicked on the UI')
			}}
		/>
	</UiEntity>
)
```

배경의 모든 속성을 자유롭게 사용할 수도 있습니다. variant를 설정한 다음 일부 속성을 재정의하는 것도 가능합니다. 이 예제에서는 `primary` variant를 사용하면서 색상을 녹색으로 재정의합니다:

```tsx
import { Button } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
	<Button
		value="My Button!"
		variant="primary"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			console.log('Clicked on My Button!')
		}}
		uiBackground={{
			color: Color4.Green(),
		}}
	/>
)
```

## 전환 가능한 버튼

버튼을 스위치처럼 두 상태 간에 전환하도록 만드는 것은 일반적인 사용 사례입니다. 아래 예제에서는 버튼을 누를 때마다 두 색상 사이를 전환합니다.

```tsx
import { Button } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

let buttonEnabled = false

export const uiMenu = () => (
	<Button
		value="내 버튼"
		variant="primary"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			console.log('Clicked on My Button!')
			buttonEnabled = !buttonEnabled
			if (buttonEnabled) {
				// 작업 수행
			} else {
				// 다른 작업 수행
			}
		}}
		uiBackground={{
			color: buttonEnabled ? Color4.Green() : Color4.Red(),
		}}
	/>
)
```

위 예제에서는 색상이 다음에 따라 달라집니다. `buttonEnabled` 변수. 이 변수의 값이 바뀌면 배경색도 즉시 바뀝니다.

## 마우스 오버 피드백

또 다른 일반적인 사용 사례는 버튼 위에 마우스를 올렸을 때 시각적 힌트를 표시하여 버튼을 클릭할 수 있음을 알려 주거나, 버튼의 기능을 설명하는 힌트를 표시하는 것입니다. 플레이어의 커서가 버튼 위에 있는지 감지하고 그에 따라 반응하려면 다음을 사용하세요. `onMouseEnter` 및 `onMouseLeave` 콜백.

```tsx
import { Button } from '@dcl/sdk/react-ecs'

let buttonEnabled = false

export const uiMenu = () => (
	<Button
		value="내 버튼"
		uiTransform={{ width: 100, height: 100 }}
		onMouseDown={() => {
			// 버튼 함수
		}}
		onMouseEnter={() => {
			// 힌트 표시
		}}
		onMouseLeave={() => {
			// 힌트 숨기기
		}}
	/>
)
```

## 다른 요소를 클릭 가능하게 만들기

UI의 모든 요소에 `onMouseDown` 속성을 추가하면 클릭 가능하게 만들 수 있으며, 버튼과 동일하게 작동합니다. 다음 예제에서는 배경 이미지와 텍스트에 `onMouseDown` 속성을 추가합니다.

```tsx
import { UiEntity, Label, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'
import { engine, Transform } from '@dcl/sdk/ecs'

export const uiMenu = () => (
	<UiEntity
		onMouseDown={() => {
			console.log('Background clicked!')
		}}
		uiTransform={{
			width: 400,
			height: 230,
		}}
		uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
	>
		<Label
			onMouseDown={() => {
				console.log('Label clicked!')
			}}
			value={`Player: ${getPlayerPosition()}`}
			fontSize={18}
			uiTransform={{ width: '100%', height: 30 }}
		/>
	</UiEntity>
)

function getPlayerPosition() {
	const playerPosition = Transform.getOrNull(engine.PlayerEntity)
	if (!playerPosition) return 'unknown'
	const { x, y, z } = playerPosition.position
	return `{x: ${x.toFixed(2)}, y: ${y.toFixed(2)}, z: ${z.toFixed(2)} }`
}
```

## 포인터 차단

모든 UI 엔터티는 기본적으로 포인터를 차단하지 않습니다. 즉, 플레이어가 클릭하면 클릭이 UI를 통과해 뒤쪽 3D 월드 공간의 객체와 상호작용합니다. 엔터티에 `onMouseDown` 콜백이 있으면 포인터를 차단하므로 플레이어의 클릭이 해당 UI 엔터티 뒤에 있는 요소에 영향을 주지 않습니다.

다음 값을 변경하면 이 기본 동작을 바꿀 수 있습니다. `pointerFilter` 속성은 `uiTransform` UI 엔터티의 컴포넌트입니다. 예를 들어, `onMouseDown` 가 없는 엔터티를 포인터 차단 상태로 설정하려면 다음과 같이 합니다.

지원되는 `pointerFilter` 값은 다음과 같습니다.

* `block`: UI 요소가 포인터를 차단하므로 플레이어는 이 UI 요소 뒤에 있는 것을 클릭할 수 없습니다.
* `none`: UI 요소가 포인터를 차단하지 않습니다. 요소 자체는 클릭할 수 없지만, 뒤에 있는 것은 클릭할 수 있습니다.

다음은 `onMouseDown`이 없지만, `pointerFilter` 를 `block`.

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

// draw UI
export const uiMenu = () => (
	<UiEntity
		uiTransform={{
			width: '100%',
			height: '100px',
			pointerFilter: `block`,
		}}
		uiText={{ value: `This element is pointer blocking`, fontSize: 40 }}
		uiBackground={{ color: Color4.create(0.5, 0.8, 0.1, 0.6) }}
	/>
)
```

### 포인터 차단은 보이는 픽셀이 아니라 레이아웃 상자를 기준으로 합니다

차단 요소는 **전체 사각형**에서 클릭을 가로챕니다. 그 위치에 실제로 그려진 것이 있는지는 상관없습니다. 배경이 완전히 투명해도 달라지지 않습니다.

{% hint style="danger" %}
**경고:** 전체 화면 크기의 래퍼에는 포인터 핸들러나 `pointerFilter: 'block'` 을 절대 설정하지 마세요. `100%` 를 기준으로 크기가 정해지는 `100%`.

사각형이 화면 전체를 차지하므로, 실수로 `onMouseDown` 을 레이아웃 루트에 설정하면 다른 모든 UI 요소와 3D 월드의 모든 항목을 클릭할 수 없게 됩니다. 패널이 화면의 작은 부분만 차지해 UI가 겉보기에는 완벽하게 정상으로 보이므로, 문제를 알아채기 매우 어렵습니다.
{% endhint %}

핸들러는 패널, 버튼, 행처럼 꼭 필요한 가장 작은 요소에 연결하세요. 레이아웃 래퍼에는 핸들러를 설정하지 마세요.

전체 화면 차단 요소가 적절한 경우는 두 가지이며, 둘 다 의도적으로 사용하는 경우입니다.

* 모달 **배경**. 클릭을 가로채도록 설계되었으며 모달이 열려 있을 때만 렌더링합니다.
* 드래그 **해제 감지 요소**. 드래그가 진행 중일 때만 존재합니다. 아래의 [드래그 상호작용](#drag-interactions) 을 참조하세요.

씬 어디에서든 클릭이 작동하지 않으면 가장 먼저 이것부터 확인하세요.

## 드래그 상호작용

UI 포인터 핸들러(`onMouseDown`, `onMouseUp`, `onMouseEnter`, `onMouseLeave`)는 매개변수를 받지 않습니다. 단순한 `() => void` 콜백으로 실행되며 위치나 좌표 데이터는 전달하지 않습니다. UI 시스템에는 `onMouseDrag` 또는 `onMouseMove` 핸들러가 없습니다.

드래그 기반 UI(슬라이더, 스크럽 바, 드래그 핸들)를 만들려면 `PrimaryPointerInfo.screenDelta` 를 `@dcl/sdk/ecs`에서 사용하세요. 이 값은 커서가 어디에 있든 매 프레임 업데이트되며, 마지막 프레임 이후의 마우스 이동량을 픽셀 단위로 제공합니다.

패턴은 다음과 같이 작동합니다.

1. `onMouseDown` 을 드래그 대상에 설정해 드래그를 시작하고 초기 값을 기록합니다.
2. 시스템에서 매 프레임 `screenDelta` 를 읽고 드래그가 활성화된 동안 값을 누적합니다.
3. pointerFilter: 'block' `이 설정된 전체 화면 투명 오버레이가` 마우스 버튼을 놓는 동작을 감지하므로, 좁은 대상 영역 밖에서 마우스를 놓아도 드래그가 종료됩니다.

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

let dragging = false
let sliderValue = 0.5

// 드래그 이동량을 누적하기 위해 이 시스템을 매 프레임 호출합니다
engine.addSystem(() => {
	if (!dragging) return

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

	// 화면 픽셀을 0–1 범위로 변환합니다
	// 드래그 속도가 커서와 일치하도록 UI 배율로 나눕니다
	const canvas = UiCanvasInformation.getOrNull(engine.RootEntity)
	const scale = canvas ? Math.min(canvas.width / 1920, canvas.height / 1080) : 1
	const trackWidth = 200 // 슬라이더 트랙의 가상 픽셀 너비

	sliderValue = Math.max(0, Math.min(1, sliderValue + delta.x / scale / trackWidth))
})
```

{% hint style="warning" %}
**참고:** 모바일에서는 `screenDelta` 가 항상 0을 반환합니다(자유롭게 움직이는 커서가 없습니다). 모바일 호환 슬라이더를 만들려면 드래그 트랙과 함께 단계 조절 버튼(`-` / `+`)을 추가하세요. UI 분기에는 [`isMobile()`](/creator/content-creator-ko/build-for-mobile/develop/detect-platform.md) 을 `@dcl/sdk/platform` 에서 가져와 사용하세요.
{% endhint %}

{% hint style="info" %}
**팁:** 항상 `screenDelta` UI 배율을 기준으로 해야 합니다. 그렇지 않으면 가상 크기와 해상도가 다른 화면에서 드래그 거리가 지나치거나 부족할 수 있습니다.
{% 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/2d-ui/ui_button_events.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.
