> 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/npc-avatars.md).

# NPC 头像

显示并控制 NPC 头像

在场景中将头像显示为一个实体。

{% hint style="info" %}
**💡 提示**：如需更轻松地处理 NPC，尤其是需要通过对话树进行交互时，请试试 [NPC Toolkit 库](https://github.com/decentraland-scenes/dcl-npc-toolkit) 。
{% endhint %}

## 创建头像

以下代码片段会创建一个头像，其穿戴物品和体型随机生成，名称为 "NPC"。

```ts
const myAvatar = engine.addEntity()
AvatarShape.create(myAvatar)

Transform.create(myAvatar, {
	position: Vector3.create(4, 0.25, 5),
})
```

传入数据以生成 `AvatarShape`时，以下字段为必填项：

* `id`：（必填）头像的内部标识符。 `id` 的最后 4 个字符会显示在 NPC 名称后方，颜色较浅，类似玩家钱包地址的后缀。 `id` 少于 4 个字符时会显示 `0000`。为每个 NPC 选择一个 `id` ，使其结尾与名称连起来读起来顺口，例如 `'guide-0001'`.

以下可选字段也可使用：

* `name`：显示在头像头顶的名称。默认值为 "NPC"。将其设为空字符串可隐藏名称；如果只想在 NPC 上方显示 [Avatar Nametag](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-nametags.md) 铭牌，这会很有用。
* `bodyShape`：用于指定体型的字符串。有效选项为 'urn:decentraland:off-chain:base-avatars:BaseMale' 和 'urn:decentraland:off-chain:base-avatars:BaseFemale'。
* `wearables`：包含头像当前穿戴物品 URN 的数组。如果穿戴物品互相冲突（例如其中两件都是帽子），列表中靠后的物品会替换前面的物品。
* `emotes`：包含头像可播放的 NFT 表情 URN 的数组
* `eyeColor`: *Color3* ，用于设置眼睛颜色（可使用任意颜色）
* `skinColor`: *Color3* ，用于设置肤色（可使用任意颜色）
* `hairColor`: *Color3* ，用于设置头发颜色（可使用任意颜色）
* `talking`：如果 *true*，则会在名称旁显示一组绿色条形图，效果类似玩家在游戏世界中使用语音聊天时的显示。
* <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p><strong>💡 提示</strong>：请参阅 <a href="https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md">颜色类型</a> ，了解如何设置颜色。</p></div>

{% hint style="warning" %}
**📔 注意**：该 `AvatarShape`组件必须通过以下方式导入：

> `import { AvatarShape } from "@dcl/sdk/ecs"`

有关如何轻松处理这些内容，请参阅 [导入](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 。
{% endhint %}

{% hint style="warning" %}
**📔 注意**：URN 字段必须遵循与 [NFTShapes](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/display-a-certified-nft.md): `urn:decentraland:<CHAIN>:<CONTRACT_STANDARD>:<CONTRACT_ADDRESS>:<TOKEN_ID>`
{% endhint %}

## 移动 NPC

要移动 NPC，请更改 `position` 其 `Transform`。化身不会瞬间跳到新位置，而是从当前位置步行过去，速度约为每秒 4 米；当目标距离达到或超过 1.5 米时，移动速度会更快。移动时，它会转向行进方向。 `rotation` 你在 `Transform` 中设置的值只有在它到达后才会应用。

```ts
// NPC 从当前位置走到新位置
Transform.getMutable(myAvatar).position = Vector3.create(10, 0.25, 5)
```

要自行控制移动，请使用一个 [补间动画](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/move-entities.md)。对位置应用补间动画会替代这种自动行走，而对旋转应用补间动画则会阻止 NPC 转向其行走的方向。一个实体一次只能有一个补间动画，因此无法同时对同一实体的位置和旋转应用补间动画。

## 动画

静止时，化身会播放默认的待机动画。

若要在化身上播放动画，请将 `expressionTriggerId` 字符串设为要播放的动画名称。

```ts
const myAvatar = engine.addEntity()
AvatarShape.create(myAvatar, {
	id: 'dancer-0001',
	emotes: [],
	wearables: [],
	expressionTriggerId: 'robot',
})

Transform.create(myAvatar, {
	position: Vector3.create(4, 0.25, 5),
})
```

该 `expressionTriggerId` 字段支持所有 [默认动画](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-animations.md#default-animations)，以及自定义动画 [（来自场景文件）](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-animations.md#custom-animations)，甚至支持已发布到市场的表情动作 URN。

要使用自定义动画，请提供 `_emote.glb` 项目根文件夹中的文件，例如 `'assets/animations/Cheer_emote.glb'`。与 [`triggerSceneEmote()`](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-animations.md#custom-animations)一样，路径错误时不会播放任何内容。

{% hint style="warning" %}
**📔 注意**: `AvatarShape` 没有 `mask` 字段，因此一个 `expressionTriggerId` 动画始终作用于整个身体。 [仅为上半身制作动画](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-animations.md#animate-only-the-upper-body) 仅适用于玩家自己的化身，不适用于 NPC。
{% endhint %}

### 在 NPC 播放表情动作时移动它

写入化身的 `Transform.position`，或对其运行 [Tween](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/move-entities.md) ，都会取消当前播放的表情动作。化身会恢复行走循环动画，因为 Decentraland 会根据化身自上一帧以来移动的距离，计算要与哪种移动动画进行混合。

如果要在表情动作期间移动 NPC，且移动范围较小，可以考虑将移动直接烘焙到动画中，例如将根节点或臀部的移动加入 `_emote.glb` 文件。

### 循环动画

AvatarShape `上的动画` 只播放一次。如果希望化身持续循环播放某个动画，就应创建一个系统，每隔几秒让它重新播放该动画。

唯一的例外是以下循环播放的默认表情动作： `sittingChair1`, `sittingChair2`, `sittingGround1` 和 `sittingGround2`。这些动作会让 `AvatarShape` 保持姿势，无需重新播放。来自文件的自定义动画不会在 `AvatarShape`上循环播放，即使动画片段本身标记为循环也是如此，因此要持续保持自定义姿势，需要使用下面的重播模式。

使用 `expressionTriggerTimestamp` 重新播放同一个表情动作。此字段的值是一个 [Lamport 时间戳](https://en.wikipedia.org/wiki/Lamport_timestamp)，也就是说，它不是时间值，而是一个索引，每重复播放一次表情动作，该索引就加 1。

因此，首次播放表情动作时，将 `expressionTriggerTimestamp` 设为 *0*。要再次播放该表情动作，必须将此值更新为 1。引擎借此判断这是一条新指令，而不是已经执行过的指令。

以下代码片段创建了一个系统，每 2 秒播放一次同一个表情动作：

```ts
const myAvatar = engine.addEntity()
AvatarShape.create(myAvatar, {
	id: 'fan-0001',
	emotes: [],
	wearables: [],
	expressionTriggerId: 'clap',
    expressionTriggerTimestamp: 0
})

Transform.create(myAvatar, {
	position: Vector3.create(4, 0.25, 5),
})

let clapTimer = 0
let emoteDuration = 2  // 2 seconds

// system
engine.addSystem((dt: number) => {
    clapTimer += dt
      
    if (clapTimer >= emoteDuration) {
        // Trigger the clap emote
        AvatarShape.getMutable(myAvatar).expressionTriggerTimestamp += 1
        
        clapTimer = 0 // Reset timer
    }
})
```

{% hint style="info" %}
**💡 提示**：你必须知道表情动作的时长，并将系统的运行时长设为相同的值。如果创建的表情动作会让化身固定保持同一个姿势，建议将表情动作的时长设得比系统更长。这样可以确保动画结束并重置时不会出现瑕疵。
{% endhint %}

## 在名称上方添加标签

使用 `AvatarNametag` 组件可在 NPC 名称上方显示带有自定义文本的标牌，例如“店主”或“头目”等角色称号。将它附加到与包含 `AvatarShape`:

```ts
AvatarNametag.create(myAvatar, { label: 'Shopkeeper' })
```

如果 `AvatarShape` 的 `name`为空，则只显示标牌，不会在下方显示空的名牌框。这适合只用称号标记 NPC。

{% hint style="info" %}
**💡 提示**：如需显示没有文字的彩色标牌，请将 `label` 设为空格字符串，并设置 `backgroundColor`。空格会保留，因此空格越多，标牌越宽。

```ts
AvatarNametag.create(myAvatar, {
	label: '      ',
	backgroundColor: Color3.Red(),
})
```

{% endhint %}

请参阅 [头像名牌](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/avatar-nametags.md) ，查看完整字段列表，包括颜色设置。

## 复制玩家的可穿戴物品

以下代码片段会将 NPC 头像的可穿戴物品及其他特征改为与玩家当前穿戴的内容一致。这可用于在场景中创建一个人体模型，展示特定的可穿戴物品，或展示与玩家当前穿搭相配的表情动作。

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


export function swapAvatar(avatar: Entity) {

  let userData = getPlayer()
  console.log(userData)

  if (!userData || !userData.wearables) return

  const mutableAvatar = AvatarShape.getMutable(avatar)

  mutableAvatar.wearables = userData.wearables
  mutableAvatar.bodyShape = userData.avatar?.bodyShapeUrn
  mutableAvatar.eyeColor = userData.avatar?.eyesColor
  mutableAvatar.skinColor = userData.avatar?.skinColor
  mutableAvatar.hairColor = userData.avatar?.hairColor
  
}
```

## 仅显示可穿戴物品

使用 `showOnlyWearables` 字段仅显示头像上列出的可穿戴物品，其余身体部分将不可见。

```ts
const myAvatar = engine.addEntity()
AvatarShape.create(myAvatar, {
	id: 'mannequin-0001',
	emotes: [],
	wearables: [
    'urn:decentraland:matic:collections-v2:0x90e5cb2d673699be8f28d339c818a0b60144c494:0'
  ],
	showOnlyWearables: true,
})

Transform.create(myAvatar, {
	position: Vector3.create(4, 0.25, 5),
})
```

这对于展示可穿戴物品很有用，例如在商店中展示。

{% hint style="info" %}
**💡 提示**：如果可穿戴物品比较小，可以尝试将 `scale` （ `Transform` 组件的）设为更大的值。
{% endhint %}

## 将实体附加到 NPC

你可以使用 `AvatarAttach` 此功能可将实体固定到 NPC 化身的某个骨骼上，例如让 NPC 手持物体。化身播放动画时，该实体也会随之移动。

要使用此功能，请使用 `id` 属性，在 `AvatarShape` 上为此化身分配任意 ID，然后在 `AvatarAttach`中引用该 ID。ID 可以是任意字符串。

```ts
// 创建 NPC，并为其设置 ID
const myAvatar = engine.addEntity()
Transform.create(myAvatar, {
  position: Vector3.create(8, 0.25, 8),
})
AvatarShape.create(myAvatar, {
  id: "my-avatar-id", 
  wearables: [],
  emotes: []
})

// 创建要附加到 NPC 的物体
const attachedEntity = engine.addEntity()
Transform.create(attachedEntity, {
    position: Vector3.create(4, 2, 4),
    scale: Vector3.create(0.15,0.15,0.15)
})
MeshRenderer.setBox(attachedEntity)
Material.setBasicMaterial(attachedEntity, { diffuseColor: Color4.Blue() })
AvatarAttach.create(attachedEntity, {
    avatarId: "my-avatar-id",
    anchorPointId: AvatarAnchorPointType.AAPT_LEFT_HAND
})
```

详细了解 `AvatarAttach` 组件，请参阅 [此处](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/entity-positioning.md#attach-an-entity-to-an-avatar).

## 替换玩家的化身

你无法更改玩家化身所穿戴的可穿戴物品，但可以将玩家的化身替换为可完全自定义的 NPC 化身。

为此，请使用 [Avatar Modifier Area](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/tou-xiang/modifier-areas.md#hide-avatars) 隐藏玩家自己的化身，并使用 `AMT_HIDE_AVATARS` 修饰符，然后在玩家所在位置显示一个 `AvatarShape` 实体。

{% hint style="warning" %}
**📔 注意**：若要让玩家完全控制该化身，应监听按钮事件以检测玩家何时按下按钮，然后触发 NPC 化身上对应的动画。更多详情请参阅 [按钮事件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/jiao-hu-xing/an-niu-shi-jian/system-based-events.md) 。

采用这种方式时，控制的流畅度可能不够理想；建议仅在非常特定的情况下使用。
{% 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/npc-avatars.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.
