> 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/3d-nei-rong-ji-chu/3d-model-animations.md).

# 3D 模型动画

如何为场景中的 3D 模型制作动画

采用 *.glTF* 和 *.glb* 格式的 3D 模型可以包含任意数量的动画。动画通过指定一系列 *关键帧* 来告知网格如何移动。关键帧按时间排列，网格随后在不同姿势之间进行混合，以模拟连续运动。

大多数 3D 模型动画都是 [*骨骼动画*](https://en.wikipedia.org/wiki/Skeletal_animation)。这类动画会将模型复杂的几何结构简化为“骨架”，并将网格中的每个顶点关联到最近的 *骨骼* 上，构成 *骨架*。建模者调整骨架摆出不同姿势，网格则会随之拉伸和弯曲。

另一种选择是， *顶点动画* 无需骨架即可为模型制作动画。这类动画会直接指定模型中每个顶点的位置。Decentraland 也支持这类动画。

有关如何为 3D 模型创建动画的详细信息，请参阅 [动画](https://github.com/decentraland/docs/blob/main/creator/3d-modeling/animations.md) 。有关如何将 3D 模型导入场景的说明，请参阅 [形状组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/shape-components.md) 。

{% hint style="info" %}
**💡 提示**：动画通常更适合让物体在原地移动，而不是改变实体的位置。例如，你可以通过动画让角色的双脚原地迈步；但若要改变实体的位置，最好使用 Transform 组件。更多详情请参阅 [定位实体](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/move-entities.md) 。
{% endhint %}

## 检查 3D 模型是否包含动画

并非所有 *glTF* 文件都包含动画。要查看文件中是否有可用动画，可以采用以下方法：

* 如果使用 [VS Code](https://code.visualstudio.com/)（推荐），请安装 *GLTF Tools* 扩展，然后在其中查看 glTF 文件的内容。
* 打开 [Babylon Sandbox](https://sandbox.babylonjs.com/) 网站，并将 glTF 文件（以及任何 *.jpg* 或 *.bin* 依赖文件）拖到浏览器中。
* 用文本编辑器打开 *.glTF* 文件，然后向下滚动，直到找到 *"animations":*.

{% hint style="info" %}
**💡 提示**：在 *骨骼* 动画中，动画名称通常由骨架名称、下划线和动画名称组成。例如 `myArmature_animation1`.
{% endhint %}

## 自动播放

如果 3D 模型包含动画，默认情况下会始终循环播放其中的第一个动画。

若要避免此行为，请向包含模型的实体添加 `Animator` 组件，然后显式处理动画的播放。如果实体中存在 `Animator` 组件，则所有动画默认都处于 `playing: false` 状态，需要手动播放。

{% hint style="info" %}
**💡 提示**：在 [场景编辑器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/ru-men/about-editor.md)中，你可以通过可视化方式添加 **Animator** 组件。请参阅 [添加组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/gou-jian/components.md#add-components)。你也可以通过 **Actions**以无代码方式控制动画，请参阅 [让任意物品变得智能](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/jiao-hu-xing/make-any-item-smart.md).
{% endhint %}

## 显式处理动画

可以使用 `Animator` 组件访问实体的所有动画，并显式指示实体播放或停止动画。该 `Animator` 组件包含一个 `states`数组，其中必须为 3D 模型可执行的每个动画添加一个对象。单个 `Animator` 可以根据需要包含任意数量的状态。

```ts
// 创建实体
const shark = engine.addEntity()

// 向其添加 3D 模型
GltfContainer.create(shark, {
	src: 'models/shark.glb',
})

Animator.create(shark, {
	states: [
		{
			clip: 'swim',
			playing: true,
			loop: true,
		},
	],
})
```

每个 `state` 对象都会跟踪动画当前是否正在播放。

{% hint style="warning" %}
**📔 注意**： `Animator` 组件必须通过以下语句导入：

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

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

## 获取动画

使用 `Animator` 组件的名称，通过 `.Animator.getClip()` 函数获取动画片段。此函数会返回动画状态对象的可变版本。

```ts
const swimAnim = Animator.getClip(sharkEntity, 'swim')
```

`Animator.getClip` 需要以下参数：

* `entity`：你想查询的 `Animator` 组件所属的实体。
* `clipName`：要获取的动画片段名称字符串。

`Animator.getClip` 会获取动画状态的可变版本，因此你可以自由修改此函数返回值中的各项值。

```ts
const swimAnim = Animator.getClip(sharkEntity, 'swim')
swimAnim.loop = false
```

{% hint style="warning" %}
**📔 注意**：如果你尝试使用 `Animator.getClip()` 获取一个未列在 `Animator` 组件中的动画片段，就会引发错误。如果希望在这种情况下返回 `Animator.getClipOrNull()` 而不是报错，以便获取 `null` ，请使用该方法。
{% endhint %}

## 播放动画

动画状态中的 `.playing` 字段用于确定动画当前是否正在播放。请注意，一个 3D 模型中可能同时播放多个动画。

对 `Animator.playSingleAnimation()` 对象调用 `AnimationState` 函数。

```ts
Animator.playSingleAnimation(sharkEntity, 'swim')
```

如果该实体正在播放其他动画， `Animator.playSingleAnimation` 会停止这些动画。

`Animator.playSingleAnimation` 需要以下参数：

* `entity`：要操作的 `Animator` 组件所属的实体。
* `clipName`：要播放的动画片段名称字符串。
* `resetCursor`: *（可选）* 如果 *true*，则从头播放动画，即使该动画之前已暂停。如果 *false*，则从暂停的位置继续播放动画。默认值： *true*.

```ts
Animator.playSingleAnimation(sharkEntity, 'swim', false)
```

下表总结了 `Animator.playSingleAnimation()` 在 `resetCursor` 属性取不同值时的行为：

|              | `resetCursor` = *false* | `resetCursor` = *true* （默认） |
| ------------ | ----------------------- | --------------------------- |
| **正在播放**     | 无效果。                    | 从头开始播放。                     |
| **已暂停**      | 从上次播放的帧继续。              | 从头开始播放。                     |
| **已结束（不循环）** | 从头开始播放。                 | 从头开始播放。                     |

## 循环播放动画

默认情况下，动画会循环播放，不断重复。

通过设置 `loop` 属性来更改此设置，该属性位于 `state` 对象中。

```ts
Animator.create(shark, {
	states: [
		{
			clip: 'bite',
			playing: true,
			loop: false,
		},
	],
})
```

如果 `loop` 设为 *false*，动画只播放一次，然后停止，并停留在最后一帧的姿势。

## 停止动画

若要停止实体正在播放的所有动画，请使用 `Animator.stopAllAnimations()`.

```ts
Animator.stopAllAnimations(shark)
```

`Animator.stopAllAnimations` 需要以下参数：

* `entity`：要操作的 `Animator` 组件所属的实体。
* `resetCursor`: *（可选）* 如果 *true*，则会恢复到动画第一帧的姿势。如果 *false*，则会暂停在当前姿势。默认值： *true*.

{% hint style="warning" %}
**📔 注意**：使用 `Animator.playSingleAnimation`播放动画时，此函数会在后台处理停止其他所有动画。此时无需显式停止其他动画。
{% endhint %}

非循环动画播放完毕后，默认情况下，3D 模型会保持在最后的姿势。 `shouldReset` 属性用于控制再次播放已停止的动画时会发生什么：如果 *true*，动画会恢复到初始状态（第一帧；如果以负 `speed`）播放，则恢复到最后一帧）。每当动画从停止状态切换为播放状态时，都会如此。如果 *false* （默认值），则会从停止时的位置继续播放。

```ts
Animator.create(shark, {
	states: [
		{
			clip: 'bite',
			playing: true,
			shouldReset: true,
			loop: true,
		},
	],
})
```

你也可以随时使用 `Animator.stopAllAnimations()` ，将姿势显式重置为动画的第一帧。

{% hint style="warning" %}
**📔 注意**：重置姿势会造成突兀的变化。如果你想让模型平滑过渡到另一种姿势，可以播放另一个动画，并逐渐调整两个动画的 `weight` 属性，在它们之间进行混合。请参阅 [动画权重](#animation-weight).
{% endhint %}

## 检测动画何时结束

非循环动画播放结束后，引擎会将该动画状态的 `playing` 属性重置为 *false*。场景代码可以读取此值，以判断动画何时结束，例如在动画结束后立即衔接播放另一个动画。

```ts
let wasPlaying = false

engine.addSystem(() => {
	const animator = Animator.get(shark)
	const biteState = animator.states.find((state) => state.clip === 'bite')
	const isPlaying = biteState?.playing ?? false

	if (wasPlaying && !isPlaying) {
		console.log('bite animation finished')
		// chain the next animation
		Animator.playSingleAnimation(shark, 'swim')
	}

	wasPlaying = isPlaying
})
```

{% hint style="warning" %}
**📔 注意**：每帧轮询动画状态时，务必通过 `Animator.get()` （只读）读取。不要使用 `Animator.getClip()` 或 `Animator.getMutable()` 进行轮询：这些方法会返回组件的可变版本，每帧都会将其标记为已更改，从而造成不必要的同步开销。

只有在动画自行结束时，引擎才会切换 `playing` 属性。循环动画会持续播放，直到被停止，因此不会自行切换该属性；而 `speed` 设为 0 的动画永远不会结束。
{% endhint %}

{% hint style="warning" %}
**📔 注意**：此功能仅支持桌面客户端。
{% endhint %}

## 处理多个动画

如果一个 3D 模型中包含多个动画，单个 `Animator` 组件即可处理所有动画。

```ts
// 创建实体
const shark = engine.addEntity()

// 向其添加 3D 模型
GltfContainer.create(shark, {
	src: 'models/shark.glb'
})

Animator.create(shark, {
	states:[{
			clip: "swim",
			playing: true,
			loop: true
		}, {
			clip: "bite",
			playing: true,
			loop: true
		}
	]
})
```

在上面的示例中，两个动画由不同的 `state` 对象处理，然后都赋给同一个 `Animator` 组件。

动画中的每根骨骼一次只能受一个动画影响，除非这些动画的 `weight` 之和不超过 1。

如果一个动画只影响角色的腿，另一个只影响角色的头部，那么它们可以同时播放，不会有任何问题。但如果两个动画都影响角色的腿，那么你必须一次只播放一个，或者以较低的 `weight` 值播放它们。

如果在上面的示例中， `bite` 动画只影响鲨鱼的嘴部，而 `swim` 动画只影响鲨鱼脊柱的骨骼，那么它们就可以同时播放。

{% hint style="warning" %}
**📔 注意**: `Animator.playSingleAnimation()` 会停止实体当前正在播放的所有其他动画。若要同时播放多个动画，请手动修改动画状态中的 `playing` 属性。
{% endhint %}

## 动画速度

通过更改 `speed` 属性来调整动画播放速度。默认速度值为 1。

```ts
Animator.create(shark, {
	states: [
		{
			clip: 'swim',
			playing: true,
			loop: true,
			speed: 2,
		},
	],
})
```

将速度设为低于 1 的值可减慢播放速度，例如设为 0.5 可让动画以一半的速度播放。将速度设为高于 1 的值可加快播放速度，例如设为 2 可让动画以双倍速度播放。

```ts
const swimAnim = Animator.getClip(sharkEntity, 'swim')

swimAnim.speed = 0.5
```

## 动画权重

weight `weight` 属性允许单个模型同时执行多个动画，并对动画涉及的所有动作进行加权平均计算。 `weight` 的值决定该动画在平均计算中所占的比重。

默认情况下， `weight` 等于 *1*。 `weight` 的值不能高于 *1*.

```ts
Animator.create(shark, {
	states: [
		{
			clip: 'swim',
			playing: true,
			loop: true,
			weight: 0.2,
		},
	],
})
```

实体中所有活动动画的 `weight` 值之和应始终为 1。如果总和小于 1，加权平均的剩余部分将使用骨架的默认姿势进行计算。

例如，在上面的代码示例中，我们正在播放 *swim* 动画，其 `weight` 仅为 *0.2*。这种游泳动作会相当轻微：强度只有动画定义值的 20%。计算中剩余的 80% 将取自骨架的默认姿势。

该 `weight` 属性可以用一些有趣的方式使用，例如 `weight` 的属性 *游泳* 可以根据鲨鱼的游动速度按比例设置，这样就不必为快速游泳和慢速游泳分别创建多个动画。

你也可以逐渐改变 `weight` 值，在动画开始和停止时让过渡更加自然，并避免从默认姿势突然跳到动画的第一个姿势。

{% hint style="warning" %}
**📔 注意**：添加到作用于 3D 模型骨骼的所有动画中的 `weight` 值之和不能超过 1。如果多个动画同时影响相同的骨骼，则需要将它们的权重设为总和小于 1 的值。
{% endhint %}

```ts
const swimAnim = Animator.getClip(sharkEntity, 'swim')

swimAnim.weight = 0.5
```


---

# 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/3d-nei-rong-ji-chu/3d-model-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.
