Particles
Particle effects with the ParticleEmitter Game Object: one texture, one config, and a pool of particles it updates and draws.
Source: src/gameobjects/particles/ParticleEmitter.js (the JSDoc at the top lists every value format), Particle.js, EmitterOp.js, GravityWell.js, ParticleProcessor.js, zones/, events/, typedefs/ParticleEmitterConfig.js. Related: animations, game-object-components, filters-and-postfx, graphics-and-shapes.
Quick start
create ()
{
// A white dot texture, so this needs no files
const g = this.make.graphics({}, false);
g.fillStyle(0xffffff);
g.fillCircle(8, 8, 8);
g.generateTexture('dot', 16, 16);
g.destroy();
const { width, height } = this.scale;
// Flow: emits every frame until stopped
this.add.particles(width / 2, height - 100, 'dot', {
speed: { min: 200, max: 400 },
angle: { min: 250, max: 290 }, // degrees, 270 is up
gravityY: 400,
lifespan: 2000,
scale: { start: 0.6, end: 0 },
blendMode: 'ADD'
});
// Burst: made idle at (0, 0), then fired at world positions
const sparks = this.add.particles(0, 0, 'dot', {
emitting: false,
speed: { min: 100, max: 300 },
lifespan: 800,
scale: { start: 0.8, end: 0 }
});
this.input.on(Phaser.Input.Events.POINTER_DOWN, (pointer) =>
{
sparks.explode(30, pointer.worldX, pointer.worldY);
});
}
this.add.particles(x, y, texture, config)returns aParticleEmitter. There is no ParticleEmitterManager and nocreateEmitter: make one emitter per effect.- The emitter is a Game Object:
setDepth,setScrollFactor,setBlendMode,setVisible,destroy, and it can go in a Container or Layer. - With a texture atlas, pick frames with
frame: 'red',frame: [ 'red', 'blue' ](random), orframe: { frames: [ ... ], cycle: true, quantity: 4 }.
Positions are relative to the emitter
Particles are drawn through the emitter's transform, so the emitter's position, scale and rotation apply to every live particle.
explode(count, x, y)andemitParticleAt(x, y, count)take positions relative to the emitter. Keep a burst emitter at (0, 0) and pass world positions, as above.- Moving the emitter moves its live particles with it. A trail should stay where it was left, so keep the emitter at (0, 0) and use
startFollow. - The config
xandy, emit zones and gravity wells are relative to the emitter too. A position given toexplode, or a followed target, replaces the configxandy, unless they are stepped. - Death zones,
boundsandviewBoundsare in world space.
Value formats
Most config keys take any of these. Keys marked "emit" in the table below are only set on emit; the others also change over the particle's life.
const config = {
speed: 200, // fixed
angle: [ 0, 90, 180, 270 ], // one, at random
lifespan: { min: 500, max: 1000 }, // random float, add int: true for an integer
quantity: { random: [ 1, 4 ] }, // random integer
scale: { start: 1, end: 0, ease: 'Quad.easeOut' }, // over the particle's life
alpha: { start: 0.2, end: 1, random: true }, // random start between the two, then to end
x: { values: [ 0, 50, -50, 0 ], interpolation: 'catmull' }, // through a list over its life
y: { steps: 8, start: 0, end: 400, yoyo: true }, // each particle at the next step
rotate: (particle, key) => Phaser.Math.Between(0, 360), // a function: called on emit
bounce: {
onEmit: (particle, key) => 0.5,
onUpdate: (particle, key, t, value) => value * 0.99 // t is 0 to 1 over its life
}
};
An onEmit callback, or a plain function, gets only (particle, key) and must return the value. Old examples wrote (particle, key, t, value) => value, which returns undefined and makes the property NaN. Only onUpdate gets t and the current value.
Config
The full list, with types, is src/gameobjects/particles/typedefs/ParticleEmitterConfig.js.
| Key | Default | Notes |
|---|---|---|
emitting |
true |
false makes it idle until start() or explode() |
frequency |
0 |
ms between emissions. 0 is every frame; -1 is explode mode |
quantity |
1 |
Particles per emission (emit) |
lifespan |
1000 |
ms (emit) |
speed |
0 |
With angle (emit). speedX and speedY instead set radial: false |
angle |
{ min: 0, max: 360 } |
Degrees (emit) |
scale, scaleX, scaleY |
1 |
scale sets both |
alpha |
1 |
|
rotate |
0 |
Degrees |
tint |
0xffffff |
WebGL only. Don't use start/end with it: use color |
color, colorEase |
An array of colors the particle moves through over its life. WebGL only | |
tintMode |
Phaser.TintModes.MULTIPLY |
Applies to every particle. WebGL only |
gravityX, gravityY |
0 |
Pixels per second per second |
accelerationX/Y, maxVelocityX/Y, bounce |
0, 10000, 0 |
|
moveToX, moveToY |
Set both: each particle travels to that point over its life | |
delay |
0 |
ms a new particle waits, visible and still, before it moves and ages (emit) |
hold |
0 |
ms a particle stays, frozen, after its life ends (emit) |
maxAliveParticles |
0 |
The most alive at once. 0 is no limit |
maxParticles |
0 |
The most it ever creates, alive and dead: once reached it emits no more. Use maxAliveParticles to cap what's on screen |
duration, stopAfter |
0 |
Stop after this many ms, or this many particles |
advance |
0 |
ms to run at once, so the effect is already going on the first frame |
reserve |
Particles to create up front | |
anim |
Animation key(s) each particle plays. See animations | |
follow, followOffset, trackVisible |
See the trail below | |
blendMode |
0 |
Such as 'ADD' |
setConfig(config) replaces the config. updateConfig(config) merges into it, but currently adds the config's emit zones, death zones and bounds a second time (an engine issue). If you will call updateConfig, add those with addEmitZone, addDeathZone and addParticleBounds instead of in the config. There are setters for live changes: setParticleSpeed, setParticleScale, setParticleGravity, setParticleAlpha, setParticleTint, setParticleLifespan, setEmitterAngle, setQuantity, setFrequency, setEmitterFrame, setAnim.
Flow and bursts
const emitter = this.add.particles(0, 0, 'dot', { speed: 100, lifespan: 500 });
emitter.start(); // flow again; fires 'start'
emitter.stop(); // no new particles, the live ones finish; fires 'stop'
emitter.stop(true); // and kill the live ones
emitter.flow(100, 5); // 5 particles every 100 ms
emitter.explode(20); // 20 at once, at the emitter, and switches to explode mode
emitter.pause(); // freezes everything; resume() continues
emitter.killAll();
COMPLETE fires when the last particle dies, but only once the emitter isn't emitting. An emitter made with the default emitting: true stays emitting after explode(), so make burst emitters with emitting: false.
A one-shot explosion that removes itself:
const boom = this.add.particles(0, 0, 'dot', {
emitting: false,
speed: { min: 150, max: 400 },
lifespan: { min: 400, max: 900 },
scale: { start: 1, end: 0 },
color: [ 0xffffff, 0xffd040, 0xff6020, 0x402020 ],
blendMode: 'ADD'
});
boom.explode(40, this.scale.width / 2, this.scale.height / 2);
boom.once(Phaser.GameObjects.Particles.Events.COMPLETE, () => boom.destroy());
For explosions that happen often, keep one emitter and call explode each time, rather than making new ones.
Trails and confetti
const ship = this.add.image(this.scale.width / 2, 600, 'dot').setScale(2).setDepth(1);
const trail = this.add.particles(0, 0, 'dot', {
speed: 20,
frequency: 20,
lifespan: 600,
scale: { start: 0.5, end: 0 },
alpha: { start: 0.8, end: 0 }
});
trail.startFollow(ship); // (target, offsetX, offsetY, trackVisible)
const confetti = this.add.particles(0, 0, 'dot', {
emitting: false,
tint: [ 0xff4040, 0xffd040, 0x40ff80, 0x40a0ff, 0xff40ff ], // one each, at random
speed: { min: 300, max: 600 },
angle: { min: 240, max: 300 },
gravityY: 600,
scaleX: 0.6,
scaleY: 0.3,
rotate: { start: 0, end: 1080 },
lifespan: 3000
});
confetti.explode(80, this.scale.width / 2, this.scale.height);
startFollow(target)emits attarget.x + offsetX,target.y + offsetY, in the emitter's space, so leave the emitter at (0, 0).stopFollow()ends it.trackVisiblehides the emitter when the target is hidden.
Color and tint
tintandcolorare WebGL only. The Canvas renderer draws particles untinted.- For a color change over a particle's life use
color: [ ... ], which blends each channel.tint: { start, end }blends the packed numbers, which gives the wrong colors. tintModereplaced v3'stintFill.tintMode: Phaser.TintModes.FILLmakes each particle a solid shape of its tint. The modes are in game-object-components.
Zones
const { width, height } = this.scale;
// Rain: random points along a line above the screen
this.add.particles(0, -10, 'dot', {
emitZone: { type: 'random', source: new Phaser.Geom.Rectangle(0, 0, width, 1) },
speedY: { min: 300, max: 500 },
lifespan: 3000,
scaleX: 0.1,
scaleY: 0.6,
deathZone: { type: 'onEnter', source: new Phaser.Geom.Rectangle(0, height - 40, width, 40) }
});
// 48 points around a circle, in order
this.add.particles(width / 2, height / 2, 'dot', {
emitZone: { type: 'edge', source: new Phaser.Geom.Circle(0, 0, 150), quantity: 48 },
speed: 20,
lifespan: 1500
});
- A
randomzone needs a source withgetRandomPoint(point): Circle, Ellipse, Rectangle, Triangle, Line, or your own object. A Polygon has nogetRandomPoint, so it is dropped without a warning. - An
edgezone needsgetPoints(quantity, stepRate): any Geom shape, Curve or Path. Its options arequantity,stepRate,yoyo,seamless(defaulttrue) andtotal. - A death zone's source needs
contains(x, y).onEnterkills particles inside it,onLeavekills those outside it. It emitsDEATH_ZONE. - With several emit zones, the emitter moves to the next one after
totalparticles. A random zone'stotalis-1, so with several random zones only the first is used. Settotalon each zone thataddEmitZonereturns:emitter.addEmitZone([ a, b ]).forEach(zone => zone.total = 10). bounds: { x, y, width, height }withbouncekeeps particles in a world-space rectangle.collideLeft,collideRight,collideTopandcollideBottomdefault totrue.
Gravity wells and processors
const emitter = this.add.particles(this.scale.width / 2, 300, 'dot', { speed: 100, lifespan: 4000 });
// x and y are relative to the emitter. power defaults to 0, which does nothing
const well = emitter.createGravityWell({ x: 200, y: 0, power: 2, epsilon: 100, gravity: 50 });
well.power = -1; // pushes away
well.active = false;
class Wind extends Phaser.GameObjects.Particles.ParticleProcessor
{
constructor (force)
{
super(0, 0, true);
this.force = force;
}
update (particle, delta, step, t)
{
// step is delta in seconds, so this is pixels per second per second
particle.velocityX += this.force * step;
}
}
emitter.addParticleProcessor(new Wind(200));
- Processors run each frame for each live particle, after its velocity and position are updated.
removeParticleProcessorremoves one. - A custom particle class,
particleClass: MyParticle, can overrideupdate(delta, step, processors). It returnstruewhen the particle is dead, so return whatsuper.updatereturned. emitCallback,deathCallback(oronParticleEmit,onParticleDeath) run for each particle.forEachAlive(callback)visits the live ones.emitter.overlap(target)returns the live particles overlapping a Rectangle or an Arcade Body.
Rendering
sortProperty: 'y'(withsortOrderAsc, defaulttrue) orsortCallback: (a, b) => a.y - b.ysorts the particles before drawing.setSortProperty(property, ascending)andsetSortCallback(callback)change it. Both were broken before 4.3. With neither set, nothing is sorted (since 4.3). New particles draw on top unlessparticleBringToTop: false.emitter.viewBounds = new Phaser.Geom.Rectangle(x, y, w, h)(world space) skips drawing the emitter when the Camera can't see that area.getBounds(padding, advance)measures the particles; withadvanceit runs the emitter forward to do so.- Filters (
emitter.enableFilters()) and lighting (emitter.setLighting(true)) need WebGL. See filters-and-postfx and lighting. setMaskis Canvas only. In WebGL, mask an emitter with the Mask filter: see masks-and-stencils.
Events
On the emitter, from Phaser.GameObjects.Particles.Events:
| Constant | String | Listener gets | When |
|---|---|---|---|
START |
'start' |
(emitter) |
start(), or a config with emitting true |
STOP |
'stop' |
(emitter) |
stop(), or duration or stopAfter reached |
COMPLETE |
'complete' |
(emitter) |
The last particle died after it stopped emitting |
EXPLODE |
'explode' |
(emitter, particle) |
explode() |
DEATH_ZONE |
'deathzone' |
(emitter, particle, zone) |
A death zone killed a particle |
Gotchas
frequency: 0means every frame, not never. Useemitting: falsefor an idle emitter.speedsets both axes fromangle.speedX/speedYswitch offradial, andangleis then ignored.active: falseorpause()freezes the whole emitter.emitting: falseonly stops new particles.delay,hold,lifespan,durationandfrequencyare in ms.- The emitter needs a texture:
new Error('Particle has no texture frame')means the key or frame is wrong.
