> 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-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-animations.md).

# 头像动画

让玩家的头像播放默认或自定义动画，并检测某个表情动作何时结束

你可以在场景代码中让玩家执行动画。这有助于增强沉浸感，也有助于向其他玩家传达彼此正在做什么。玩家本人（在第三人称视角下）和周围的其他玩家都能看到这些头像动画。

由玩家控制的全身动画会被默认的移动动画（例如行走和跳跃）覆盖。因此，场景播放的全身动画只会在玩家静止站立时播放。如果玩家行走或跳跃，任何全身动画都会中断。上半身动画不会因移动而中断。

{% hint style="warning" %}
**📔 注意**：只有当玩家已经站在场景边界内时，才能为其播放动画；如果玩家位于相邻场景，则无法播放。智能可穿戴设备可以在任何位置播放动画。

玩家执行动画期间不会受到碰撞影响，其移动也不受场景物理效果的限制。另请注意，如果动画使玩家偏离原始位置（例如，动画包含跳跃动作），玩家的 Transform 组件不会受到这种位移的影响。
{% endhint %}

### 使用场景编辑器

让玩家执行动画最简单的方法是使用场景编辑器。使用无代码 **播放表情动作** 操作来播放默认动画，或使用 **播放自定义表情动作** 操作来播放文件中的动画。请参阅 [将任意物品设为智能物品](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/make-any-item-smart.md).

### 默认动画

使用 `triggerEmote()` 函数来运行 Decentraland 中玩家可以随时播放的默认动画之一。此函数接受一个包含以下属性的对象作为参数：

* `predefinedEmote`：现有表情动作的字符串名称。
* `mask`：（可选）使用 `AvatarMask` 枚举中的值，仅在头像身体的一部分播放动画。例如， `AvatarMask.AM_UPPER_BODY` 仅为头像的上半身播放动画。请参阅 [仅为上半身播放动画](#animate-only-the-upper-body).

```ts
import { triggerEmote } from '~system/RestrictedActions'

const emoter = engine.addEntity()
Transform.create(emoter, { position: Vector3.create(8, 0, 8) })
MeshRenderer.setBox(emoter)
MeshCollider.setBox(emoter)
pointerEventsSystem.onPointerDown(
	{
		entity: emoter,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Dance' },
	},
	() => {
		triggerEmote({ predefinedEmote: 'robot' })
	}
)
```

以下表情动作会反馈玩家在场景中的操作，这些值都可用于 `predefinedEmote` 字段：

* `buttonDown`
* `buttonFront`
* `getHit`
* `knockOut`
* `lever`
* `openChest`
* `openDoor`
* `punch`
* `push`
* `swingWeaponOneHand`
* `swingWeaponTwoHands`
* `throw`
* `sittingChair1`
* `sittingChair2`
* `sittingGround1`
* `sittingGround2`

四种 `sitting` 表情动作会循环播放：玩家移动或场景调用 `stopEmote({})`. `stopEmote` 会以 `{ success: boolean }`作为结果，其中 `false` 表示 Explorer 拒绝了该调用，例如玩家已不在你的场景中。其他动作都只播放一次，随后头像会恢复待机状态。

所有玩家都可以在默认表情动作轮盘中使用这些表情动作，也可以在任何场景中使用。

* `wave`
* `fistpump`
* `robot`
* `raiseHand`
* `clap`
* `money`
* `kiss`
* `tik`
* `hammer`
* `tektonik`
* `dontsee`
* `handsair`
* `shrug`
* `disco`
* `dab`
* `headexplode`
* `crafting`
* `handsintheair`
* `Victory`
* `Waving`
* `fistpump_short`

`cry` 和 `dance` 也是 `predefinedEmote`的有效值，尽管 Creator Hub 的 **Avatar Animations** 资源包中没有列出它们。

{% hint style="warning" %}
**📔 注意**：请严格使用此处列出的名称。名称错误时，场景中不会有任何提示：动作不会播放，场景控制台也不会显示任何内容。请特别留意 `handsintheair` 中间没有分隔符，以及 `fistpump_short` 末尾带有后缀。
{% endhint %}

{% hint style="info" %}
**💡 提示**：如果玩家在动画播放期间行走或跳跃，就会打断动画。如果不希望玩家这样做，可以通过冻结头像来实现。 [输入修饰符](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/locomotion.md#freeze-the-player) 在头像动画持续期间。
{% endhint %}

### 自定义动画

使用 `triggerSceneEmote()` 让玩家执行自定义动画。动画以 .glb 文件的形式存储，并作为场景资源的一部分。

{% hint style="info" %}
**💡 提示**：这些动画无需自己制作。场景编辑器中的 **头像动画** 资源包提供了 45 种现成动画，包括坐姿、钓鱼、搬箱子和跳舞。将动画拖到 3D 视图中，编辑器便会将其文件复制到场景中；然后将该文件的路径传递给 `triggerSceneEmote()`。文件会存放在 `assets/asset-packs/<animation-folder>/`下，例如 `assets/asset-packs/whack/Whack_Avatar_emote.glb`。请在 **本地资源**中查看确切路径。另请参阅 [添加物品](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/ru-men/about-editor.md#avatar-animations).
{% endhint %}

{% hint style="warning" %}
**📔 注意**：文件名 **必须** 以 `_emote.glb` 结尾，才能用作头像动画。
{% endhint %}

此函数接受一个包含以下属性的对象：

* `src`：表情动画文件的完整路径，以项目根目录为起点。例如，位于 `assets/animations/sit_emote.glb` 的文件需要使用 `'assets/animations/sit_emote.glb'`.
* `loop`：如果为 true，动画将持续循环，直到玩家移动或动画停止。默认值为 false。
* `mask`：（可选）使用 `AvatarMask` 枚举中的值，仅在头像身体的一部分播放动画。例如， `AvatarMask.AM_UPPER_BODY` 仅为头像的上半身播放动画。请参阅 [仅为上半身播放动画](#animate-only-the-upper-body).

{% hint style="warning" %}
**📔 注意**: `src` 必须是文件的完整路径。系统不会按文件名搜索，也不会为你添加 `_emote` 后缀。如果路径错误， `triggerSceneEmote()` 将返回 `{ success: false }` ，且不会播放任何内容。请从项目文件夹复制路径，并确保包含其中的所有文件夹。
{% endhint %}

```ts
import { triggerSceneEmote } from '~system/RestrictedActions'
import { AvatarMask } from '@dcl/sdk/ecs'

const emoter = engine.addEntity()
Transform.create(emoter, { position: Vector3.create(8, 0, 8) })
MeshRenderer.setBox(emoter)
MeshCollider.setBox(emoter)
pointerEventsSystem.onPointerDown(
	{
		entity: emoter,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Make snowball' },
	},
	() => {
		triggerSceneEmote({ src: 'assets/animations/Snowball_Throw_emote.glb', loop: false, mask: AvatarMask.AM_UPPER_BODY })
	}
)
```

{% hint style="info" %}
**💡 提示**：如果玩家在动画播放期间行走或跳跃，就会打断动画。如果不希望玩家这样做，可以通过冻结头像来实现。 [输入修饰符](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/locomotion.md#freeze-the-player) 在头像动画持续期间。
{% endhint %}

#### 道具、粒子和音效

使用 `triggerSceneEmote()` 播放的表情动画文件可以包含道具（例如网球拍）或火焰喷射效果，并与头像一起进行动画处理。请按照 Emotes 2.0 表情动画的制作方式构建，并遵循以下命名规则： [道具与音效](https://docs.decentraland.org/creator/content-creator-zh/chuan-dai-wu-yu-biao-qing-dong-zuo/biao-qing-dong-zuo/props-and-sounds.md):

* 该文件包含两个动画片段：一个名称中包含 `_Avatar` ，用于角色；另一个名称中包含 `_Prop` ，用于道具骨架。
* 两个片段的时长相同。
* 将粒子效果转换为动画骨骼后即可正常工作，详见 [表情动作中的粒子效果](https://docs.decentraland.org/creator/content-creator-zh/chuan-dai-wu-yu-biao-qing-dong-zuo/biao-qing-dong-zuo/particles-in-emotes.md).

周围的其他玩家能看到这些道具，就像能看到角色动画一样。

{% hint style="warning" %}
**📔 注意**: `triggerSceneEmote()` 不会播放声音。只有在 Builder 中作为独立表情上传的表情才会播放音频。要将声音与场景表情配对，请同时使用 [AudioSource](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/sounds.md) 播放。
{% endhint %}

### 仅动画上半身

两者 `triggerEmote()` 和 `triggerSceneEmote()` 接受一个可选的 `mask` 属性，用于将动画限制在角色身体的特定部位。

通常，玩家一走路或跳跃，动画就会停止，因为默认的移动动画会接管整个身体。当你将 `mask` 设为 `AvatarMask.AM_UPPER_BODY`时，动画只会驱动角色腰部以上的部分，而双腿仍由默认的移动动画控制。这意味着玩家可以在场景中继续行走或奔跑，同时播放上半身动画。对于不应打断移动的动作，可以使用此功能，例如搬运板条箱、举着火把或抛接杂耍。

```ts
import { triggerSceneEmote } from '~system/RestrictedActions'
import {
	engine,
	AvatarMask，
	InputAction,
	MeshCollider,
	MeshRenderer,
	pointerEventsSystem,
	Transform,
} from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

const cheerButton = engine.addEntity()
Transform.create(cheerButton, { position: Vector3.create(8, 0, 8) })
MeshRenderer.setBox(cheerButton)
MeshCollider.setBox(cheerButton)
pointerEventsSystem.onPointerDown(
	{
		entity: cheerButton,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Cheer' },
	},
	() => {
		triggerSceneEmote({
			src: 'assets/animations/Cheer_emote.glb',
			loop: true,
			mask: AvatarMask.AM_UPPER_BODY,
		})
	}
)
```

在此示例中，玩家点击按钮后，角色便会举起双臂开始欢呼，并循环播放动画。由于动画只作用于上半身，角色在欢呼时仍可在场景中四处奔跑，例如在赛车或足球比赛中追随赛事进程。

请注意以下几点：

* `AvatarMask.AM_UPPER_BODY` 目前是 `AvatarMask` 枚举中的唯一值。若要播放全身动画，只需不设置 `mask` 属性。
* 该 `loop` 属性的行为与全身动画相同：设置 `loop: false` 被遮罩的动画播放一次后，上半身会恢复正常移动状态，设置 `loop: true` 则会持续重复，直到停止。
* 若要通过代码停止循环播放的被遮罩动画，请调用 `stopEmote({})`，该函数也从 `~system/RestrictedActions`导入。调用结果为 `{ success: boolean }`.

### 检测表情动作何时结束

每个表情动作生命周期事件都会通过玩家实体上的 `AvatarEmoteCommand` 组件报告。每个新条目都包含一个 `state` 字段，其值来自 `EmoteState` 枚举：

* `EmoteState.ES_STARTED`：表情动作开始播放。若缺少 `state` 字段，报告的值也会是此值。
* `EmoteState.ES_FINISHED`：非循环表情动作自然播放至结束。
* `EmoteState.ES_INTERRUPTED`：表情动作被中断：玩家移动或跳跃、传送、开始播放其他表情动作、主动停止表情动作，或离开场景。

此功能适用于由场景触发的表情动作（通过`triggerEmote()` 和 `triggerSceneEmote()`），也适用于玩家通过表情动作轮盘自行播放的动作，以及场景中其他玩家播放的动作。

使用 `onChange` 函数监听 `AvatarEmoteCommand` 组件，以响应每个新条目：

```ts
import { AvatarEmoteCommand, EmoteState } from '@dcl/sdk/ecs'

export function main() {
	AvatarEmoteCommand.onChange(engine.PlayerEntity, (emote) => {
		if (!emote) return

		switch (emote.state ?? EmoteState.ES_STARTED) {
			case EmoteState.ES_STARTED:
				console.log('emote started: ', emote.emoteUrn)
				break
			case EmoteState.ES_FINISHED:
				console.log('emote finished naturally: ', emote.emoteUrn)
				break
			case EmoteState.ES_INTERRUPTED:
				console.log('emote was interrupted: ', emote.emoteUrn)
				break
		}
	})
}
```

{% hint style="warning" %}
**📔 注**：此功能仅在桌面客户端中受支持。本地玩家播放的带有 `mask` （身体局部表情动作）的表情动作目前不会报告生命周期事件。
{% endhint %}

{% hint style="info" %}
**💡 提示**：要在非玩家的化身上播放动画，请参阅 [NPC 化身](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/npc-avatars.md#animations).
{% 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-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-animations.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.
