Work in progress

The content of this page was not yet updated for Godot 4.2 and may be outdated. If you know how to improve this page or you can confirm that it's up to date, feel free to open a pull request.

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).

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

../../_images/particles_convert.webp

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.png

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.png

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…):

Приклад текстури фліпчарту частинок

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.

preprocess()

Системи частинок починаються з нуля випромінюваних частинок, потім починають випромінювати. Це може бути незручністю, при завантаженні сцени та систем, таких як факел, імла тощо, коли вони починають випромінювати частинки в момент входу. Попередня обробка використовується для того, щоб система могла обробити задану кількість секунд до того, як вона фактично буде намальована вперше.

Масштаб

Шкала швидкості за замовчуванням має значення 1 і використовується для регулювання швидкості системи частинок. Зменшення значення призводить до того, що частинки будуть повільнішими, а збільшення значення - до їх прискорення.

Вибуховість

Якщо час життя становить 1 і є 10 частинок, це означає, що одна частинка буде випромінюватися кожні 0,1 секунди. Параметр вибуховості змінює це і змушує частинки випромінюватися одночасно. Діапазони:

  • 0: Випускати частинки через рівні проміжки часу (значення за замовчуванням).

  • 1: Випускати всі частинки одночасно.

Також допускаються значення в середині. Ця функція корисна для створення вибухів або раптових викидів частинок:

../../_images/paranim18.gif

Випадковість

Всі фізичні параметри можуть бути випадковими. Випадкові значення варіюються від 0 до 1. Формула для параметра випадковості:

initial_value = param_value + param_value * randomness

Фіксована частота кадрів

Цей параметр можна використовувати для налаштування рендерингу системи частинок із фіксованим FPS. Наприклад, зміна значення на 2 змусить частинки відтворюватися зі швидкістю 2 кадри в секунду. Зауважте, це не уповільнює саму систему частинок.

Фракт Дельта

Цим можна увімкнути або вимкнути Fract Delta.

Параметри малювання

Прямокутник видимості

Прямокутник видимості контролює видимість частинок на екрані. Якщо цей прямокутник знаходиться за межами області перегляду, движок не відображатиме частинки на екрані.

Властивості прямокутника, 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.

Ви можете регулювати тривалість випромінювання за допомогою опції Час генерації (сек). Максимальне значення - 25 секунд. Якщо вам потрібно більше часу для переміщення частинок, ви можете тимчасово змінити тривалість на вузлі Particles2D.

Локальні координати

За замовчуванням цей параметр увімкнений, і це означає, що простір, куди випромінюються частинки, визначається відносно вузла. Якщо вузол переміщений, усі частинки переміщуються разом з ним:

../../_images/paranim20.gif

Якщо його вимкнути, частинки будуть випромінюватися у глобальний простір, це означає, що переміщення вузла, не вплине на вже випущені частинки:

../../_images/paranim21.gif

Порядок малювання

Це контролює порядок малювання окремих частинок. Index означає, що частинки малюються відповідно до їх порядку викидання (за замовчуванням). Lifetime означає, що вони малюються в порядку часу, що залишився до кінця життя.

ParticleProcessMaterial settings

Напрямок

Це основний напрямок, в якому випромінюються частинки. За замовчуванням Vector3(1, 0, 0), це означає, що частинки випромінюються вправо. Однак, з налаштуванням сили тяжіння за замовчуванням, частинки будуть падати вниз.

../../_images/direction1.png

Щоб ця властивість була помітною, вам потрібна початкова швидкість, більша за 0. Тут ми встановлюємо початкову швидкість до 40. Ви помітите, що частинки випромінюються вправо, а потім опускаються через гравітацію.

../../_images/direction2.png

Розсіювання

Spread (Розсіювання) - кут у градусах, який буде випадковим чином доданий в будь-якому напрямку до основного напряму. Розсіювання 180 буде випромінюватися в усіх напрямках (+/- 180). Щоб розсіювання працювало, параметр Initial Velocity (Початкова швидкість) повинен бути більше 0.

../../_images/paranim3.gif

Пласкість

Ця властивість корисна лише для 3D-частинок.

Тяжіння

Гравітація, що застосовується до кожної частинки.

../../_images/paranim7.gif

Ініціалізувати

Це швидкість, з якою будуть випромінюватися частинки (у пікселях/сек). Пізніше швидкість може бути змінена під дією сили тяжіння або інших прискорень (як описано далі).

../../_images/paranim4.gif

Кутова швидкість

Це початкова кутова швидкість, що застосовується до частинок.

Spin Velocity (Швидкість Обертання)

Швидкість, з якою частинки обертаються навколо свого центру (у градусах/с).

../../_images/paranim5.gif

Орбітальний вид праворуч

Використовується, щоб змусити частинки повертати відносно їх центру.

../../_images/paranim6.gif

Linear Acceleration (Лінійне прискорення)

Лінійне прискорення, прикладене до кожної частинки.

Radial Acceleration (Радіальне прискорення)

Якщо це прискорення позитивне, частинки прискорюються далеко від центру. Якщо негативне, вони поглинаються ним.

../../_images/paranim8.gif

Tangential Acceleration (Дотичне прискорення)

Це прискорення використовуватиме дотичний вектор до центру. Поєднання з радіальним прискоренням може принести хороші ефекти.

../../_images/paranim9.gif

В’язкість

Застосовує до частинок тертя, змушуючи їх зупинитися. Це особливо корисно для іскор або вибухів, які зазвичай починаються з високою лінійною швидкістю, а потім припиняються в міру згасання.

../../_images/paranim10.gif

Кут

Визначає початковий кут частинки (у градусах). Цей параметр переважно корисний випадковим.

../../_images/paranim11.gif

Масштаб

Визначає початковий масштаб частинок.

../../_images/paranim12.gif

Колір

Використовується для зміни кольору частинок, що виділяються.

Hue Variation

Значення Variation задає початкову зміну колірного тону застосованого до кожної частинки. Значення Variation Random визначає коефіцієнт варіації колірного тону випадковістю.

Анімація

Примітка

Particle flipbook animation is only effective if the CanvasItemMaterial used on the GPUParticles2D or CPUParticles2D node has been configured accordingly.

To set up the particle flipbook for linear playback, set the Speed Min and Speed Max values to 1:

Setting up particle animation for playback during the particle's lifetime

Setting up particle animation for playback during the particle's lifetime

By default, looping is disabled. If the particle is done playing before its lifetime ends, the particle will keep using the flipbook's last frame (which may be fully transparent depending on how the flipbook texture is designed). If looping is enabled, the animation will loop back to the first frame and resume playing.

Depending on how many images your sprite sheet contains and for how long your particle is alive, the animation might not look smooth. The relationship between particle lifetime, animation speed, and number of images in the sprite sheet is this:

Примітка

At an animation speed of 1.0, the animation will reach the last image in the sequence just as the particle's lifetime ends.

\[Animation\ FPS = \frac{Number\ of\ images}{Lifetime}\]

If you wish the particle flipbook to be used as a source of random particle textures for every particle, keep the speed values at 0 and set Offset Max to 1 instead:

Setting up particle animation for random offset on emission

Setting up particle animation for random offset on emission

Note that the GPUParticles2D node's Fixed FPS also affects animation playback. For smooth animation playback, it's recommended to set it to 0 so that the particle is simulated on every rendered frame. If this is not an option for your use case, set Fixed FPS to be equal to the effective framerate used by the flipbook animation (see above for the formula).

Emission Shapes (Форми Випромінювання)

ParticleProcessMaterials allow you to set an Emission Mask, which dictates the area and direction in which particles are emitted. These can be generated from textures in your project.

Ensure that a ParticleProcessMaterial is set, and the GPUParticles2D node is selected. A "Particles" menu should appear in the Toolbar:

../../_images/emission_shapes1.png

Відкрийте його та виберіть "Завантажити маску випромінювання":

../../_images/emission_shapes2.png

Потім виберіть, яку текстуру ви хочете використовувати як маску:

../../_images/emission_shapes3.png

З'явиться діалогове вікно з декількома налаштуваннями.

Маска випромінювання

З текстури можна створити три типи масок випромінювання:

  • Залиті пікселі: Частинки виникають з будь-якої області текстури, за винятком прозорих областей.

../../_images/emission_mask_solid.gif
  • Крайні Пікселі: Частинки виникають із зовнішніх країв текстури.

../../_images/emission_mask_border.gif
  • Направлені крайні пікселі: схожі на крайні пікселі, але додають додаткову інформацію до маски, щоб дати частинкам здатність випромінюватись далеко від меж. Запримітьте, що для того, щоб використовувати їх, потрібно встановити Початкову швидкість.

../../_images/emission_mask_directed_border.gif

Кольори випромінювання

Capture from Pixel призведе до того, що частинки успадкують колір маски в місцях їх появи.

Once you click "OK", the mask will be generated and set to the ParticleProcessMaterial, under the Emission Shape section:

../../_images/emission_shapes4.png

Всі значення в цьому розділі були автоматично сформовані за допомогою меню Завантажити маску випромінювання, тому їх, як правило, слід залишити в спокої.

Примітка

Зображення не слід додавати безпосередньо до Point Texture або Color Texture. Натомість завжди слід використовувати меню Завантажити маску випромінювання.