engage-particle-system

1.0.5 • Public • Published

Particle System

A modular particle system for Pixi 4.8.8.

Running the example

  • Clone the repository
  • Execute npm install
  • Execute npm run dev_server
  • Navigate to localhost:3700

Documentation

The following section will go through and explain the different aspects of the particle system.

Usage

To get started using the particle system, add it as an npm dependency to your project using npm install engage-particle-system. Now import the library into your project using import * as PS from "engage-particle-system.js";.

Everything you'll need is now contained in the PS object.


Setting up a particle system

Assume a screen size of 800x600 pixels for the following guide.

The first thing you'll want to do, is create an instance of ParticleType, then assign modules to it, to define behaviour for the particle type.

// Create the particle type and assign it a name
let myParticleType = new PS.ParticleType("MyParticleType");

In this example, we'll use the following init modules:

  • InitialCirclePositionModule
  • InitialLifetimeModule
  • InitialScaleUniformModule
  • InitialVelocityModule

This will define the initial position, life-time, uniform scale, and velocity of the particle type.

// Define the init modules
myParticleType.addModule(new PS.InitialCirclePositionModule(400, 300, 80));           // The circle is in the center of the screen and has a radius of 80
myParticleType.addModule(new PS.InitialLifetimeModule(0.4, 1.0));                     // The particle will live for between 400 ms and 1 sec
myParticleType.addModule(new PS.InitialScaleUniformModule(0.2, 1.0));                 // The particle will have a scale between 0.2 and 1
myParticleType.addModule(new PS.InitialVelocityModule(PS.WORLD_RIGHT, 90, 10, 80)); // The particle will fly to the right with a spread of 90 degrees, going between 10 and 80 pixels per second

We will assign the following modify modules:

  • GravityModule
  • LifetimeScaleModule

We can use these to make the particle fall and scale down over its life-time.

// Define the modify modules
myParticleType.addModule(new Dust.GravityModule(PS.Vector.createVector2(0, 10)));

let lifetimeScaleInterpolation = new PS.Interpolation();
lifetimeScaleInterpolation.addKeyframe(0.0, 0.0)
                          .addKeyframe(0.2, 1.0)
                          .addKeyframe(0.8, 1.0)
                          .addKeyframe(1.0, 0.0);
myParticleType.addModule(new PS.LifetimeScaleModule(lifetimeScaleInterpolation));

Finally, we'll add this draw module: DrawSpriteModule.

This will pull the sprite with the given name from the loaded spritesheets and assign it to the particle when it is born. If you have multiple draw modules assigned, each particle will use its own draw module for retrieving a sprite, in a sequential order.

// Define the draw modules
myParticleType.addModule(new PS.DrawSpriteModule("MyParticleSprite"));

Now that our particle type is defined, we can create a particle system, and add the particle type to it. Finally, we can add the particle system to the stage, set a spawn rate, and start it.

// Create the particle system
let particleSystem = new PS.Emitter();
particleSystem.addParticleType(myParticleType); // The first particle type added becomes the default particle type

// Add it to the stage
stage.addChild(particleSystem);

// Set a spawn rate
particleSystem.setSpawnRate(40); // 40 particles per second

// Start the particle system
particleSystem.start();

That's it, this produces a particle system, which spawns particles within a circle in the center of the screen, with a radius of 80 pixels. The particles will have a single sprite assigned, a life-time between 400 milliseconds and 1 second, they will have a scale between 0.2 and 1.0. They will fly towards the right side of the screen with a spread of 90 degrees, at a speed between 10 and 80 pixels per second. Gravity is applied at 10 pixels per second squared. Each particle starts with a scale multiplier of 0.0, then 20% into its life, it goes to 1.0. Between 80% and 100% through its life, it goes back to 0.0.

Full example:

// Create the particle type and assign it a name
let myParticleType = new PS.ParticleType("MyParticleType");

// Define the init modules
myParticleType.addModule(new PS.InitialCirclePositionModule(400, 300, 80));           // The circle is in the center of the screen and has a radius of 80
myParticleType.addModule(new PS.InitialLifetimeModule(0.4, 1.0));                     // The particle will live for between 400 ms and 1 sec
myParticleType.addModule(new PS.InitialScaleUniformModule(0.2, 1.0));                 // The particle will have a scale between 0.2 and 1
myParticleType.addModule(new PS.InitialVelocityModule(PS.WORLD_RIGHT, 90, 10, 80)); // The particle will fly to the right with a spread of 90 degrees, going between 10 and 80 pixels per second

// Define the modify modules
myParticleType.addModule(new PS.GravityModule(PS.Vector.createVector2(0, 10)));

let lifetimeScaleInterpolation = new PS.Interpolation();
lifetimeScaleInterpolation.addKeyframe(0.0, 0.0)
                          .addKeyframe(0.2, 1.0)
                          .addKeyframe(0.8, 1.0)
                          .addKeyframe(1.0, 0.0);
myParticleType.addModule(new PS.LifetimeScaleModule(lifetimeScaleInterpolation));

// Define the draw modules
myParticleType.addModule(new PS.DrawSpriteModule("MyParticleSprite"));

// Create the particle system
let particleSystem = new PS.Emitter();
particleSystem.addParticleType(myParticleType); // The first particle type added becomes the default particle type

// Add it to the stage
stage.addChild(particleSystem);

// Set a spawn rate
particleSystem.setSpawnRate(40); // 40 particles per second

// Start the particle system
particleSystem.start();

Modules

This section will describe the different modules that exists in the system. General class documentation is included later in this document.

Module types

There are 4 different types of modules in the system.

  • Init: Runs once when a particle is born, sets the initial state of the particle.
  • Modify: Runs every update step, modifies the state of the particle.
  • Draw: Assigns a sprite to the particle when it is born.
  • Event: Runs once a given condition is met.

Module overview

The following is a short overview of all the modules included in the system.

Name Type Description
AbsolutePositionModule Init Sets the particle to an absolute position.
InitialCirclePositionModule Init Sets the particle to a random position within a circle.
InitialLinePositionModule Init Sets the particle to a random position along a given line.
InitialLifetimeModule Init Sets the particle life-time to a random value within a given range.
InitialRotationModule Init Sets the particle rotation to a random value within a given range.
InitialScaleModule Init Sets the particle scale to a random value within a given range.
InitialScaleUniformModule Init Sets the particle scale uniformly to a random value within a given range
InitialVelocityModule Init Sets the particle velocity.
DragModule Modify Applies drag to the particle, slowing it down.
GravityModule Modify Applies gravity to the particle, making it fall.
LifetimeScaleModule Modify Scales the particle over its life-time.
RotatorModule Modify Makes the particle rotate over time.
SpawnModule Modify Makes the particle emit new particles from itself.
DrawSpriteModule Draw Assigns the given sprite to the particle.
OnExpiredModule Event Calls the given callback or applies the given module, when the particle expires.
OnProgressModule Event Calls the given callback or applies the given module, when the particle life-time progress reaches the given value.

Classes

The following will describe the essential classes in the library.

Emitter

This is the main class for a particle system, this functions like the emitter and the controller of the system.

Extends: PIXI.particles.ParticleContainer

Methods:

Method signature Description
constructor() Constructs a new instance of the particle system.
void addParticleType(ParticleType particleType) Assigns the given particle type to the particle system. The first particle type added to a system, will become the default particle type for that system.
void spawn(int amount, string particleTypeName = null, Particle[] spawnedParticles = null) Spawns the given number of particles, this can be used for making burst effects. If a particle type name is given, that type is used, otherwise, the default particle type is used. If an array is given, the newly spawned particles will be added to that array.
void removeAllParticles() Removes all active particles in the particle system.
void start(bool startOwnTicker = true) Starts the particle system, this is used for making a continuous stream of particles. By default, the particle system will start its own ticker loop.
void stop(bool removeAllParticles = true) Stops the particle system. By default, all active particles will be removed when the particle system is stopped.
void tick(float deltaTime) Steps the particle system simulation forward by the given delta time (in seconds). This can be used for manually ticking the particle system, if it doesn't use an internal ticker.
void setTimescale(float timescale) Sets the timescale used by the particle system. 0 means time is frozen, 1 is normal speed, 2 is double the normal speed.
float getTimescale() Gets the timescale currently in use by the particle system.
void setSpawnRate(int spawnRate) Sets the spawn rate used by the particle system (in particles per second).
int getSpawnRate() Gets the spawn rate currently used by the particle system.
ParticleType getParticleTypeByName(string particleTypeName) Gets the particle type with the given name, if it is assigned to this particle system.

ParticleType

This is used for defining behaviour for a type of particle. This is done by adding modules to the particle type.

Methods:

Method signature Description
constructor(string name) Constructs a new particle type with the given name.
ParticleType addModule(BaseModule module) Adds the given module instance to this particle type. The particle type itself is returned, to allow chaining of this method.
void applyNextDrawModule(Particle particle, Emitter particleSystem) Applies the next draw module from this particle type, to the given particle. This is called internally by the system.

Particle

This class holds information on each particle in the system. The system will manage instances of particles for you, most methods on the particle are called internally by the system. You shouldn't have to manipulate these directly, unless you're writing new modules for the system.

Extends: PIXI.Sprite

Properties:

Property Description
Vector pos The current position of the particle.
float rot The current rotation (in radians) of the particle.
Vector sca The current scale of the particle.
Vector vel The current velocity of the particle.
float lifetime The life-time of the particle (in seconds).
float alpha The alpha / opacity of the particle.
Vector initPos The position of the particle when it was born.
float initRot The rotation of the particle when it was born.
Vector initSca The scale of the particle when it was born.
Vector initVel The velocity of the particle when it was born.
Object keyValues Used for storing module specific information on the particle. In a key-value-pair.

Methods:

Method signature Description
constructor(Emitter particleSystem) Constructs a new particle instance assigned to the given particle system.
void assignParticleType(ParticleType particleType) Assigns the given particle type to this particle.
void initialize() Initializes the particle to its starting state, init modules are also applied here.
void reset() Resets the state of the particle.
void expireNow() Makes the particle expire instantly, in other words, it becomes inactive and gets removed from the particle system.
bool isAlive() Checks if the particle is still alive and active.
float getLifetimeProgress() Gets the life-time progress of the particle. 0 Meaning the particle was just born, 1 meaning the particle has expired.
void update(float deltaTime) Steps the particle state forward by the given delta time (in seconds). Modify modules are applied here.

BaseModule

Abstract class from which all modules should inherit.

Enum: TYPE

  • Init
  • Modify
  • Draw
  • Event

Methods:

Method signature Description
constructor(BaseModule.TYPE type) Constructs a new base module instance and assigns the given type to it.
bool isInitModule() Checks if this module is an init module.
bool isModifyModule() Checks if this module is a modify module.
bool isDrawModule() Checks if this module is a draw module.
bool isEventModule() Checks if this module is an event module.
applyModule(Particle particle, Emitter particleSystem) Gets called whenever this module should apply some effect to a particle. Override this in custom modules.

Vector

Used for performing vector arithmetic. Represents a 3 dimensional vector

Properties:

Property Description
float x The x component of the vector.
float y The y component of the vector.
float z The z component of the vector.

Methods:

Method signature Description
constructor(float x, float y, float z) Constructs a new vector instance with the given x, y, and z components. This does not make use of the object pool. Use one of the static create methods instead.
void addVector(Vector vec) Adds the given vector to this vector.
void addScalar(float scalar) Adds the given scalar to each component of this vector.
void addComponents(float x, float y, float z) Adds the given x, y, and z components to this vector.
void subtractVector(Vector vec) Subtracts the given vector from this vector.
void subtractScalar(float scalar) Subtracts the given scalar from each component of this vector.
void subtractComponents(float x, float y, float z) Subtracts the given x, y, and z components from this vector.
void multiplyVector(Vector vec) Multiplies the given vector with this vector.
void multiplyScalar(float scalar) Multiplies the given scalar with each component of this vector.
void multiplyComponents(float x, float y, float z) Multiplies the given x, y, and z components with this vector.
void divideVector(Vector vec) Divides this vector by the given vector.
void divideScalar(float scalar) Divides each component of this vector by the given scalar.
void divideComponents(float x, float y, float z) Divides each component of this vector by the given x, y, and z components.
float getLengthSquared() Gets the squared length / magnitude of this vector.
float getLength() Gets the actual length / magnitude of this vector.
void release() Releases this vector instance into an object pool, for future reuse.
void normalize() Normalizes this vector to a length / magnitude of 1.
Vector clone() Creates a clone of this vector instance.

Static methods:

Static method signature Description
Vector direction(Vector from, Vector to) Gets a unit vector pointing from the given from vector to the given to vector.
float distanceSquared(Vector a, Vector b) Gets the squared distance between the two given vectors.
float distance(Vector a, Vector b) Gets the actual distance between the two given vectors.
float dot(Vector a, Vector b) Gets the dot product of the two given vectors.
Vector createVector2(float x, float y) Creates a vector with the given x and y components. Pulls it from the object pool if possible.
Vector createVector3(float x, float y, float z) Creates a vector with the given x, y, and z components. Pulls it from the object pool if possible.
Vector createZeroVector() Creates a vector with a length / magnitude of 0. Pulls it from the object pool if possible.
Vector createOneVector() Creates a vector with a length / magnitude of 1. Pulls it from the object pool if possible.
Vector createUnitRightVector() Creates a unit vector pointing to the right in world-space. Pulls it from the object pool if possible. [1, 0, 0]
Vector createUnitLeftVector() Creates a unit vector pointing to the left in world-space. Pulls it from the object pool if possible. [-1, 0, 0]
Vector createUnitUpVector() Creates a unit vector pointing up in world-space. Pulls it from the object pool if possible. [0, -1, 0]
Vector createUnitDownVector() Creates a unit vector pointing down in world-space. Pulls it from the object pool if possible. [0, 1, 0]
Vector createUnitForwardVector() Creates a unit vector pointing forward in world-space. Pulls it from the object pool if possible. [0, 0, 1]
Vector createUnitBackwardVector() Creates a unit vector pointing backwards in world-space. Pulls it from the object pool if possible. [0, 0, -1]

Interpolation

Used for interpolating between different keyframe values.

Methods:

Method signature Description
constructor() Constructs a new interpolation instance.
Interpolation addKeyframe(float position, float value) Adds a new keyframe with the given value, at the given position (in the range of 0 to 1). Returns this interpolation instance, to allow chained calls.
float getValueFromProgress(float progress) Calculates the value at the given progress / position (in the range of 0 to 1)

MathUtils

Contains different math utility methods.

Static methods:

Static method signature Description
float clamp(float value, float min, float max) Clamps the given value between the given minimum and maximum values.
float clamp01(float value) Clamps the given value between 0 and 1.
float linearInterpolate(float a, float b, float t) Calculates a linearly interpolated value from a towards b based on t.
Vector linearInterpolateVector(Vector a, Vector b, float t) Calculates a linearly interpolated vector from a towards b based on t.
float mapRange(float value, float srcMin, float srcMax, float dstMin, float dstMax) Maps the given value from one range (defined by srcMin and srcMax) to another range (defined by dstMin and dstMax).
float convertDegreesToRadians(float degrees) Converts the given angle (in degrees) to radians.
float getRandomRangeFloat(float min, float max) Gets a random float within the given range. min is inclusive, max is exclusive.
float getRandomRangeInt(int min, int max) Gets a random int value within the given range. min is inclusive, max is exclusive.

Readme

Keywords

Package Sidebar

Install

npm i engage-particle-system

Weekly Downloads

7

Version

1.0.5

License

ISC

Unpacked Size

160 kB

Total Files

30

Last publish

Collaborators

  • snengage