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

# 粒子系统

向场景添加火焰、雨、火花和魔法光环等粒子效果

粒子系统通过发射并动画化大量小型精灵图，帮助你创建动态视觉效果。你可以用它们制作火焰、烟雾、雨、雪、火花、魔法光环、爆炸以及许多其他难以通过静态网格实现的效果。

## 添加粒子系统

若要在场景中添加粒子系统，请创建一个实体并为其附加 `ParticleSystem` 组件。

```ts
import { engine, Transform, ParticleSystem } from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'

const emitter = engine.addEntity()

Transform.create(emitter, {
	position: Vector3.create(8, 1, 8),
})

ParticleSystem.create(emitter, {})
```

如果未设置任何属性，组件将使用所有默认值：点发射器每秒发射 10 个粒子，每个粒子的生命周期为 5 秒。

## 发射器形状

发射器形状决定粒子的生成位置。可通过以下方式使用四种形状： `ParticleSystem.Shape` 辅助函数。

### 点

粒子从单个点（实体的位置）生成。如果未指定形状，这是默认形状。

```ts
ParticleSystem.create(emitter, {
	shape: ParticleSystem.Shape.Point(),
})
```

### 球体

粒子从球体表面或内部生成。

```ts
ParticleSystem.create(emitter, {
	shape: ParticleSystem.Shape.Sphere({ radius: 2 }),
})
```

### 圆锥

粒子从圆锥底部生成，并沿圆锥的方向向外移动。 `angle` 是以度为单位的半角； `radius` 是以米为单位的底面半径。若要调整圆锥方向，请设置实体的 `Transform`.

```ts
ParticleSystem.create(emitter, {
	shape: ParticleSystem.Shape.Cone({ angle: 25, radius: 1 }),
})
```

### 盒体

粒子从盒体体积内部的任意位置生成。

```ts
ParticleSystem.create(emitter, {
	shape: ParticleSystem.Shape.Box({ size: Vector3.create(3, 1, 3) }),
})
```

## 发射属性

控制粒子的生成数量及其生命周期。

| 属性             | 默认值    | 描述              |
| -------------- | ------ | --------------- |
| `rate`         | `10`   | 每秒发射的粒子数（连续发射）。 |
| `maxParticles` | `1000` | 同时存活的粒子数量上限。    |
| `lifetime`     | `5`    | 每个粒子的生命周期（秒）。   |
| `active`       | `true` | 粒子系统是否正在发射新粒子。  |

```ts
ParticleSystem.create(emitter, {
	rate: 50,
	maxParticles: 500,
	lifetime: 3,
})
```

## 运动

### 重力

该 `gravity` 属性是应用于场景重力（-9.81 m/s²）的乘数。将其设为 `0` 可让粒子悬浮在原处，设为负值可将粒子向上推，设为正值则会使粒子向下加速。

```ts
ParticleSystem.create(emitter, {
	gravity: -0.5, // 粒子缓慢向上漂浮
})
```

### 初始速度

`initialVelocitySpeed` 是一个 `FloatRange` 用于设置粒子发射时随机速度范围的最小值和最大值（单位：m/s）。两个值默认均为 `1`.

```ts
ParticleSystem.create(emitter, {
	initialVelocitySpeed: { start: 2, end: 8 },
})
```

### 额外力

每帧施加到所有粒子上的恒定力向量，此外还会施加重力。适用于模拟风力或磁力效果。

```ts
ParticleSystem.create(emitter, {
	additionalForce: Vector3.create(0.5, 0, 0), // 恒定的侧向推力
})
```

### 速度限制

使用 `limitVelocity` 可限制粒子的最大速度，并可选择在每帧削减超出部分的速度。

```ts
ParticleSystem.create(emitter, {
	limitVelocity: {
		speed: 5, // 允许的最大速度，单位为 m/s
		dampen: 0.8, // 每帧削减的超出速度比例
	},
})
```

## 视觉属性

### 颜色

`initialColor` 用于设置粒子出生时的颜色，该颜色会在给定范围内随机选取。 `colorOverTime` 使粒子的颜色在其生命周期内逐渐从 `start` 值过渡到 `end` 值。两者都接受一个 `ColorRange` ，其中包含 `start` 和 `end` 值。

```ts
import { Color4 } from '@dcl/sdk/math'

ParticleSystem.create(emitter, {
	initialColor: {
		start: Color4.create(1, 0.5, 0, 1), // 橙色
		end: Color4.create(1, 1, 0, 1), // 黄色
	},
	colorOverTime: {
		start: Color4.create(0.5, 0, 0, 0.5), // 暗红色，半透明
		end: Color4.create(0, 0, 0, 0), // 完全透明（淡出）
	},
})
```

请注意， `Color4` 中的第 4 个值是 *alpha（透明度）*。如果将最终颜色的 alpha 设为 0，粒子就会逐渐淡出并变得不可见，这通常能产生不错的效果。

### 大小

`initialSize` 和 `sizeOverTime` 都是 `FloatRange` 值。 `initialSize` 控制粒子出生时的缩放比例，并在给定范围内随机取值。 `sizeOverTime` 使粒子的缩放比例在其生命周期内从 `start` 值逐渐过渡到 `end` 值。值为 `1` 时，表示使用原始纹理尺寸。

```ts
ParticleSystem.create(emitter, {
	initialSize: { start: 0.1, end: 0.3 },
	sizeOverTime: { start: 0.5, end: 1.0 }, // grow over lifetime
})
```

{% hint style="warning" %}
**📔 注意**： `scale` 实体的 `Transform` 不会影响粒子的缩放比例。
{% endhint %}

### 纹理

默认情况下，粒子会渲染为白色方块。提供纹理即可使用自定义图像。

```ts
ParticleSystem.create(emitter, {
	texture: { src: 'assets/scene/Images/spark.png' },
})
```

### 混合模式

控制粒子颜色与其后方场景的合成方式。

| 值                                      | 描述                         |
| -------------------------------------- | -------------------------- |
| `ParticleSystemBlendMode.PSB_ALPHA`    | 标准透明混合（默认）。                |
| `ParticleSystemBlendMode.PSB_ADD`      | 加法混合——粒子会使场景变亮。适用于火焰和发光效果。 |
| `ParticleSystemBlendMode.PSB_MULTIPLY` | 将粒子颜色与其后方场景的颜色相乘。          |

```ts
import { ParticleSystemBlendMode } from '@dcl/sdk/ecs'

ParticleSystem.create(emitter, {
	texture: { src: 'assets/scene/textures/ember.png' },
	blendMode: ParticleSystemBlendMode.PSB_ADD,
})
```

### 面向摄像机

当 `billboard` 为 `true` 时（默认值），每个粒子都会始终面向摄像机，不受发射器朝向影响。将其设为 `false` 可让粒子在 3D 空间中翻滚。

```ts
ParticleSystem.create(emitter, {
	billboard: false,
})
```

## 旋转

### 初始旋转和随时间变化的旋转

`initialRotation` 表示粒子生成时的朝向。 `rotationOverTime` 表示每秒应用的各轴角速度。两者都接受 `Quaternion`.

```ts
import { Quaternion } from '@dcl/sdk/math'

ParticleSystem.create(emitter, {
	initialRotation: Quaternion.fromEulerDegrees(0, 0, 45),
	rotationOverTime: Quaternion.fromEulerDegrees(0, 0, 90), // spin 90°/s on Z
})
```

{% hint style="warning" %}
**📔 注意**：如果 `billboard` 设置为 `true`，粒子就只会沿一个轴旋转，并始终保持朝向摄像机。
{% endhint %}

### 朝向运动方向

当 `faceTravelDirection` 为 `true`时，每个粒子都会自动旋转，使其指向运动方向，就像小行星或在空中飘落的树叶一样。

```ts
ParticleSystem.create(emitter, {
	faceTravelDirection: true,
	billboard: false,
})
```

{% hint style="warning" %}
**📔 注意**：如果 `faceTravelDirection` 为 true， `billboard` 的值将被忽略。
{% endhint %}

## 精灵表动画

你可以将纹理视为由动画帧组成的网格来制作粒子动画。指定精灵表中的列数和行数，以及播放速度。

```ts
ParticleSystem.create(emitter, {
	texture: { src: 'assets/scene/textures/flame-sheet.png' },
	spriteSheet: {
		tilesX: 4, // 4 列
		tilesY: 3, // 3 行（共 12 帧）
		framesPerSecond: 12,
	},
})
```

## 播放控制

粒子系统可以处于以下三种状态之一，通过 `playbackState`.

| 值                                        | 描述             |
| ---------------------------------------- | -------------- |
| `ParticleSystemPlaybackState.PS_PLAYING` | 正在发射粒子（默认状态）。  |
| `ParticleSystemPlaybackState.PS_PAUSED`  | 冻结所有现有粒子并停止发射。 |
| `ParticleSystemPlaybackState.PS_STOPPED` | 停止发射并移除所有现有粒子。 |

```ts
import { ParticleSystemPlaybackState } from '@dcl/sdk/ecs'

// 玩家走远时暂停
ParticleSystem.getMutable(emitter).playbackState =
	ParticleSystemPlaybackState.PS_PAUSED

// 恢复
ParticleSystem.getMutable(emitter).playbackState =
	ParticleSystemPlaybackState.PS_PLAYING
```

### 循环与预热

系统默认会无限循环。将 `loop` 设为 `false` 即可创建一次性效果；所有粒子消失后，效果会自动停止。

将 `prewarm` 设为 `true` （需要 `loop: true`），以模拟系统从一开始就运行的状态，这样玩家首次看到场景时，粒子就已经充满场景。

```ts
ParticleSystem.create(emitter, {
	loop: false, // 播放一次后停止
	prewarm: false,
})
```

## 爆发式发射

爆发允许你在特定时刻发射大量粒子，而不是以恒定速率发射。它们适用于爆炸、烟花或其他一次性事件。

单个粒子系统可以经历包含多次爆发的周期，还可以设置不同的间隔或概率，让效果显得更加自然。

```ts
ParticleSystem.create(emitter, {
	rate: 0, // 禁用连续发射
	bursts: {
		values: [
			{
				time: 0, // 播放开始后的秒数
				count: 200, // 每次爆发发射的粒子数
				cycles: 1, // 重复次数（0 = 无限）
				interval: 0.2, // 重复周期之间的秒数
				probability: 1, // 每个周期触发爆发的概率，范围为 0–1
			},
		],
	},
})
```

以下示例展示了一个具有交错爆发的循环烟花效果：

```ts
ParticleSystem.create(emitter, {
	loop: true,
	rate: 0,
	lifetime: 2,
	bursts: {
		values: [
			{ time: 0.0, count: 80, cycles: 0, interval: 3 },
			{ time: 0.7, count: 100, cycles: 0, interval: 3 },
			{ time: 1.4, count: 60, cycles: 0, interval: 3 },
		],
	},
})
```

## 模拟空间

控制粒子是相对于发射器移动（`PSS_LOCAL`，默认值），还是在生成后固定在世界坐标中（`PSS_WORLD`).

对于需要在移动时留下轨迹的发射器（例如小行星或火箭），请使用 `PSS_WORLD` 。

```ts
import { PBParticleSystem_SimulationSpace } from '@dcl/sdk/ecs'

ParticleSystem.create(emitter, {
	simulationSpace: PBParticleSystem_SimulationSpace.PSS_WORLD,
})
```

## 性能

引擎会限制每个场景的粒子预算。如果场景中的粒子总数可能超出限制，引擎会自动降低场景中所有活动粒子系统的发射速率。请据此规划场景：

* 优先使用数量较少、视觉效果突出的系统，而不是大量效果不明显的系统。
* 使用 `maxParticles` 限制单个系统的粒子数。
* 使用 `active` 或 `playbackState` 停用位于屏幕外或超出范围的系统。
* 较短的 `lifetime` 值可以降低存活粒子数，其效果比单看较高的发射 `rate` 值所暗示的更明显。

引擎会将任意时刻渲染的最大粒子数限制为 1000。如果发射的粒子超过此数量，你可能无法看到全部粒子。

还需注意，只有玩家身处场景内时才能看到粒子。从外部观看场景的玩家，必须进入场景后才能看到粒子。

## 粒子实验室

进入世界 [ParticleLab.dcl.eth](decentraland://?realm=particlelab.dcl.eth\&dclenv=org) ，体验不同的粒子系统。靠近粒子系统时，界面会显示所有可用字段，你可以实时调整它们，无需重新加载场景。调整满意后，点击 **复制** 按钮，即可将该粒子系统的代码复制到剪贴板。

{% hint style="info" %}
**💡 提示**：如需查看涵盖每个 `ParticleSystem` 字段的可运行示例，请参阅 [`0,7-particle-system`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/0,7-particle-system) 测试场景。它涵盖了全部四种发射器形状、 `PSB_ADD`/`PSB_ALPHA`/`PSB_MULTIPLY` 混合模式、 `PS_PLAYING`/`PS_PAUSED`/`PS_STOPPED` 播放状态、精灵图集、连续 `rate` 与单次及循环 `bursts`，以及移动发射器上的 `PSS_LOCAL` 与 `PSS_WORLD` 。
{% 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/3d-nei-rong-ji-chu/particle-system.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.
