360 Secure SkillHub
360 安全技能中心

particles

提供 Phaser 4 粒子发射器的用法、配置格式、爆发与拖尾、颜色、区域、重力井、渲染和事件说明,并给出修正旧版习惯的代码示例。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:24

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/particles
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
particles
description
Particle effects in Phaser 4: this.add.particles(x, y, texture, config) returns a ParticleEmitter Game Object (no manager). Covers the config value formats (min/max, start/end, steps, onEmit/onUpdate), flow and explode, color and tintMode, emit and death zones, gravity wells and processors, following a target, sorting and the emitter events. Use when making an explosion, sparks, confetti, smoke, fire, rain, a trail behind a ship or player, or a hit effect. Corrects old habits: ParticleEmitterManager and createEmitter are gone, tintFill is now tintMode, explode(count, x, y) and gravity wells are relative to the emitter, onEmit gets only (particle, key). Triggers on: particles, this.add.particles, ParticleEmitter, emitter, explode, burst, particle trail, confetti, emitZone, deathZone, GravityWell.
metadata
{"phaser-version":"4.3.0"}

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 a ParticleEmitter. There is no ParticleEmitterManager and no createEmitter: 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), or frame: { 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) and emitParticleAt(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 x and y, emit zones and gravity wells are relative to the emitter too. A position given to explode, or a followed target, replaces the config x and y, unless they are stepped.
  • Death zones, bounds and viewBounds are 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 at target.x + offsetX, target.y + offsetY, in the emitter's space, so leave the emitter at (0, 0). stopFollow() ends it.
  • trackVisible hides the emitter when the target is hidden.

Color and tint

  • tint and color are 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.
  • tintMode replaced v3's tintFill. tintMode: Phaser.TintModes.FILL makes 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 random zone needs a source with getRandomPoint(point): Circle, Ellipse, Rectangle, Triangle, Line, or your own object. A Polygon has no getRandomPoint, so it is dropped without a warning.
  • An edge zone needs getPoints(quantity, stepRate): any Geom shape, Curve or Path. Its options are quantity, stepRate, yoyo, seamless (default true) and total.
  • A death zone's source needs contains(x, y). onEnter kills particles inside it, onLeave kills those outside it. It emits DEATH_ZONE.
  • With several emit zones, the emitter moves to the next one after total particles. A random zone's total is -1, so with several random zones only the first is used. Set total on each zone that addEmitZone returns: emitter.addEmitZone([ a, b ]).forEach(zone => zone.total = 10).
  • bounds: { x, y, width, height } with bounce keeps particles in a world-space rectangle. collideLeft, collideRight, collideTop and collideBottom default to true.

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. removeParticleProcessor removes one.
  • A custom particle class, particleClass: MyParticle, can override update(delta, step, processors). It returns true when the particle is dead, so return what super.update returned.
  • emitCallback, deathCallback (or onParticleEmit, 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' (with sortOrderAsc, default true) or sortCallback: (a, b) => a.y - b.y sorts the particles before drawing. setSortProperty(property, ascending) and setSortCallback(callback) change it. Both were broken before 4.3. With neither set, nothing is sorted (since 4.3). New particles draw on top unless particleBringToTop: 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; with advance it runs the emitter forward to do so.
  • Filters (emitter.enableFilters()) and lighting (emitter.setLighting(true)) need WebGL. See filters-and-postfx and lighting.
  • setMask is 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: 0 means every frame, not never. Use emitting: false for an idle emitter.
  • speed sets both axes from angle. speedX/speedY switch off radial, and angle is then ignored.
  • active: false or pause() freezes the whole emitter. emitting: false only stops new particles.
  • delay, hold, lifespan, duration and frequency are in ms.
  • The emitter needs a texture: new Error('Particle has no texture frame') means the key or frame is wrong.