Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

2D particle systems

Введение

Particle systems are used to simulate complex physical effects, such as sparks, fire, magic particles, smoke, mist, etc.

Идея состоит в том, что «частица» испускается через фиксированный интервал и с фиксированным временем жизни. В течение своей жизни у каждой частицы будет одно базовое поведение. Что отличает каждую частицу от остальных и обеспечивает более натуральный вид, так это «случайность», связанная с каждым параметром. По сути, создание системы частиц означает установку основных физических параметров, а затем добавление к ним случайности.

Узлы частиц

Godot provides two different nodes for 2D particles, GPUParticles2D and CPUParticles2D. GPUParticles2D is more advanced and uses the GPU to process particle effects. CPUParticles2D is a CPU-driven option with near-feature parity with GPUParticles2D, but lower performance when using large amounts of particles. On the other hand, CPUParticles2D may perform better on low-end systems or in GPU-bottlenecked situations.

While GPUParticles2D is configured via a ParticleProcessMaterial (and optionally with a custom shader), the matching options are provided via node properties in CPUParticles2D (with the exception of the trail settings).

Going forward there are no plans to add new features to CPUParticles2D, though pull requests to add features already in GPUParticles2D will be accepted. For that reason we recommend using GPUParticles3D unless you have an explicit reason not to.

You can convert a CPUParticles2D node into a GPUParticles2D node by clicking on the node in the scene tree, selecting the 2D workspace, and selecting CPUParticles2D > Convert to GPUParticles2D in the toolbar.

../../_images/particles_convert.webp

It is also possible to convert a GPUParticles2D node to a CPUParticles2D node, however there may be issues if you use GPU-only features.

The rest of this tutorial is going to use the GPUParticles2D node. First, add a GPUParticles2D node to your scene. After creating that node you will notice that only a white dot was created, and that there is a warning icon next to your GPUParticles2D node in the scene dock. This is because the node needs a ParticleProcessMaterial to function.

ParticleProcessMaterial

To add a process material to your particles node, go to Process Material in your inspector panel. Click on the box next to Material, and from the dropdown menu select New ParticleProcessMaterial.

../../_images/particles_material.webp

Your GPUParticles2D node should now be emitting white points downward.

../../_images/particles1.png

Текстура

A particle system can use a single texture or an animation flipbook. A flipbook is a texture that contains several frames of animation that can be played back, or chosen at random during emission. This is equivalent to a spritesheet for particles.

The texture is set via the Texture property:

../../_images/particles2.webp

Using an animation flipbook

Particle flipbooks are suited to reproduce complex effects such as smoke, fire, explosions. They can also be used to introduce random texture variation, by making every particle use a different texture. You can find existing particle flipbook images online, or pre-render them using external tools such as Blender or EmberGen.

Example of a particle system that uses a flipbook texture

Example of a particle system that uses a flipbook texture

Using an animation flipbook requires additional configuration compared to a single texture. For demonstration purposes, we'll use this texture with 5 columns and 7 rows (right-click and choose Save as…):

Particle flipbook texture example

Credit: JoesAlotofthings (CC BY 4.0)

To use an animation flipbook, you must create a new CanvasItemMaterial in the Material section of the GPUParticles2D (or CPUParticles2D) node:

Creating a CanvasItemMaterial at the bottom of the particles node inspector

Creating a CanvasItemMaterial at the bottom of the particles node inspector

In this CanvasItemMaterial, enable Particle Animation and set H Frames and V Frames to the number of columns and rows present in your flipbook texture:

Configuring the CanvasItemMaterial for the example flipbook texture

Configuring the CanvasItemMaterial for the example flipbook texture

Once this is done, the Animation section in ParticleProcessMaterial (for GPUParticles2D) or in the CPUParticles2D inspector will be effective.

Совет

If your flipbook texture has a black background instead of a transparent background, you will also need to set the blend mode to Add instead of Mix for correct display. Alternatively, you can modify the texture to have a transparent background in an image editor. In GIMP, this can be done using the Color > Color to Alpha menu.

Параметры времени

Время жизни

Время в секундах, в течение которого каждая частица останется в живых. Когда время жизни заканчивается, вместо нее создается новая частица.

Продолжительность жизни: 0,5

../../_images/paranim14.gif

Продолжительность жизни: 4,0

../../_images/paranim15.gif

Одноразовый

When enabled, a GPUParticles2D node will emit all of its particles once and then never again.

Предобработка

Системы частиц начинаются с нулевого испускания частиц, а затем начинают испускаться. Это может быть неудобно при загрузке сцены и таких систем, как факел, туман и т.д., которые начинают излучаться сразу после входа. Предварительная обработка используется, чтобы позволить системе обработать заданное количество секунд до того, как она будет фактически отрисована в первый раз.

Масштаб скорости

Шкала скорости имеет значение по умолчанию 1 и используется для регулировки скорости системы частиц. Понижение значения сделает частицы медленнее, в то время как увеличение значения сделает частицы намного быстрее.

Взрывоопасность

Если продолжительность жизни равна 1 и имеется 10 частиц, это означает, что частица будет испускаться каждую 0,1 секунды. Параметр "explosiveness" меняет это и заставляет частицы испускаться все вместе. Диапазоны:

  • 0: Испускать частицы через равные промежутки времени (значение по умолчанию).

  • 1: Испускать все частицы одновременно.

Допускаются также значения в середине. Эта функция полезна для создания взрывов или внезапных выбросов частиц:

../../_images/paranim18.gif

Случайность

Все физические параметры могут быть рандомизированы. Диапазон случайных значений от 0 до ``1 ``. Формула рандомизации параметра:

initial_value = param_value + param_value * randomness

Фиксированный FPS

Этот параметр можно использовать для установки системы частиц для рендеринга с фиксированным FPS. Например, изменение значения на 2 приведет к рендерингу частиц со скоростью 2 кадра в секунду. Обратите внимание, что это не замедляет саму систему частиц.

Примечание

Godot 4.3 does not currently support physics interpolation for 2D particles. As a workaround, disable physics interpolation for the particles node by setting Node > Physics Interpolation > Mode at the bottom of the inspector.

Fract Delta

Setting Fract Delta to true results in fractional delta calculation, which has a smoother particles display effect. This increased smoothness stems from higher accuracy. The difference is more noticeable in systems with high randomness or fast-moving particles. It helps maintain the visual consistency of the particle system, making sure that each particle's motion aligns with its actual lifespan. Without it, particles might appear to jump or move more than they should in a single frame if they are emitted at a point within the frame. The greater accuracy has a performance tradeoff, particularly in systems with a higher amount of particles.

Параметры отрисовки

Видимый прямоугольник

Прямоугольник видимости контролирует видимость частиц на экране. Если этот прямоугольник находится за пределами области просмотра, движок не будет отображать частицы на экране.

Свойства прямоугольника W и H соответственно управляют его шириной и высотой. Свойства X и Y управляют положением верхнего левого угла прямоугольника относительно излучателя частиц.

You can have Godot generate a Visibility Rect automatically using the toolbar above the 2d view. To do so, select the GPUParticles2D node and Click Particles > Generate Visibility Rect. Godot will simulate the Particles2D node emitting particles for a few seconds and set the rectangle to fit the surface the particles take.

Вы можете контролировать длительность излучения с помощью опции Generation Time (sec). Максимальное значение - 25 секунд. Если вам нужно больше времени для перемещения частиц, вы можете временно изменить длительность preprocess на узле Particles2D.

Локальные координаты

По умолчанию эта опция включена, и это означает, что пространство, в которое излучаются частицы определяется относительно узла. Если узел перемещается, все частицы перемещаются вместе с ним:

../../_images/paranim20.gif

Если этот параметр отключен, частицы будут излучаться в глобальное пространство, что означает, что при перемещении узла уже испускаемые частицы не затрагиваются:

../../_images/paranim21.gif

Порядок рисования

Это контролирует порядок, в котором отрисовываются отдельные частицы. Index означает, что частицы отрисовываются в соответствии с порядком их выброса (по умолчанию). Lifetime означает, что они нарисованы в порядке оставшегося времени жизни.

Particle Process Material Settings

For information on the settings in the ParticleProcessMaterial see this page.