> 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). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 3D 模型动画

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

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

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

作为替代方案， *顶点动画* 无需骨架即可为模型制作动画。这类动画直接指定模型中每个顶点的位置。Decentraland 也支持此类动画。

详情请参阅 [动画](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) ，了解如何将 3D 模型导入场景。

{% 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.
