How do you create fire, smoke, magic and explosions? You make lots of elves, dozens, hundreds, even thousands of elves. Then apply some physics to these sprites to make them behave like the elements you’re trying to emulate. You also have to give them rules about how they should appear and disappear and what patterns they should form. These tiny sprites are called particles. You can use them to create all kinds of special effects for your game.

Use Dust library

Pixi has no built-in ability to create particle effects, but you can use a lightweight library called Dust to create them.

Note: Dust is a quick and easy way to make most of the particle effects a game needs, but if you need a more full-featured, complex library, check out Proton

Using the Dust library is the same as using the SpriteUtilities library.

First, import js files directly with script tags

<script src="https://www.kkkk1000.com/js/dust.js"></script>
Copy the code

Then create an instance of it

d = new Dust(PIXI);
Copy the code

The variable D now represents the Dust instance.

Next, call Dust’s Update method in the game loop, which is used to update particles. You can do this in the gameLoop and Play functions in the examples we made in the previous article. It is recommended to do this in gameLoop, just after calling the state function but before the render phase, as follows:

function gameLoop(){
 requestAnimationFrame(gameLoop);
 state();
 d.update();
 renderer.render(stage);
}
Copy the code

Make the particle

To make particles, use the CREATE method of the Dust library

Parameters:

The name of the type The default value describe
x number 0 The x coordinate where the particle appears
y number 0 The y coordinate where the particle appears
spriteFunction function A function that returns sprites to be used for each particle. If you provide sprites with multiple frames, Dust will randomly display different frames
container object A PIXI container The container to add particles to
numberOfParticles number 20 Number of particles to create
gravity number 0 The force of gravity
randomSpacing boolean true Random intervals
minAngle number 0 The minimum Angle
maxAngle number 6.28 Maximum Angle
minSize number 4 The minimum size
maxSize number 16 The largest size
minSpeed number 0.3 Minimum speed
maxSpeed number 3 Maximum speed
minScaleSpeed number 0.01 Minimum proportional velocity
maxScaleSpeed number 0.05 Maximum proportional velocity
minAlphaSpeed number 0.02 Minimum alpha speed
maxAlphaSpeed number 0.02 Maximum alpha velocity
minRotationSpeed number 0.01 Minimum speed of rotation
maxRotationSpeed number 0.03 Maximum rotation speed

The return value:

Returns an array containing references to all sprites used as particles, which can be useful if they must be accessed for reasons such as collision detection.

Now let’s try this.

Sample code:


      
<html lang="zn">

<head>
    <meta charset="UTF-8">
</head>

<body>
    <div id="px-render"></div>

    <script src="https://www.kkkk1000.com/js/pixi4.8.2.js"></script>
    <script src="https://www.kkkk1000.com/js/spriteUtilities.js"></script>
    <script src="https://www.kkkk1000.com/js/dust.js"></script>
    <script>
        // Some parameters needed to create a Pixi application
        let option = {
            width: 400.height: 300.transparent: true,}// Create a Pixi application
        let app = new PIXI.Application(option);
        // Get the stage
        let stage = app.stage;
        // Get the renderer
        let renderer = app.renderer;
        let playground = document.getElementById('px-render');
        // Add the canvas created by Pixi to the page
        playground.appendChild(renderer.view);

        let su = new SpriteUtilities(PIXI);
        let d = new Dust(PIXI);

        // The address of the image to load
        let imgURL = "https://www.kkkk1000.com/images/learnPixiJS-ParticleEffects/star.png";
        // Load the image, and then execute the setup function
        PIXI.loader.add(imgURL).load(setup);

        function setup() {
            stars = d.create(
                128.// start x
                128.// start y
                () => su.sprite(imgURL), // Returns the Sprite to be used for each particle
                stage, // Particle container
                50./ / particle number
                0./ / gravity
                false.// Random interval
                0.6.28.// Minimum/maximum Angle
                30.90.// Minimum/maximum size
                1.3// Minimum/maximum speed
            );

            // Start the game loop
            gameLoop();
        }

        function gameLoop() {
            requestAnimationFrame(gameLoop);
            d.update();
            renderer.render(stage);
        }
    </script>
</body>

</html>
Copy the code

See the effect

Using ParticleContainer

In the previous example code, the particles we created were added to the root container (fourth argument). However, you can add particles to any container or any other Sprite you like.

Pixi has a method called ParticleContainer, and any Sprite in the ParticleContainer will render 2 to 5 times faster than in a normal Container.

Learn about ParticleContainer here

If you want to use the ParticleContainer for particles, simply add the name of the ParticleContainer object you want to use in the fourth argument to the create method. Here is how to modify the previous example code to add particles to the ParticleContainer named starContainer.

// Create ParticleContainer and add it to the stage
let starContainer = new PIXI.particle.ParticleContainer(
    1500,
    { alpha: true.scale: true.rotation: true.uvs: true}); stage.addChild(starContainer);function setup() {
    // Create star particles and add them to starContainer
    stars = d.create(
        128.// start x
        128.// start y
        () => su.sprite(imgURL),
        starContainer, // Particle container
        50./ / particle number
        0./ / gravity
        false.// Random interval
        0.6.28.// Minimum/maximum Angle
        30.90.// Minimum/maximum size
        1.3// Minimum/maximum speed
    );

    // Start the game loop
    gameLoop();
}
Copy the code

See the effect

ParticleContainers are optimized for pushing thousands of sprites, so unless you animate a lot of particles, you probably won’t notice a performance improvement for using plain Container objects.

Use particle emitters

The CREATE method produces a particle burst, but generally you have to produce a continuous stream of particles. You can do this with the help of a particle emitter. Particle emitters produce particles at regular intervals to create a flow effect. You can use Dust’s Emitter method to create a particle emitter. Emitters have play and stop methods to turn on and off the particle stream and to define the interval between particle creation.

The following code is a general format for the Emitter method using Dust. It takes two arguments.

The first parameter is the particle creation interval in milliseconds.

The second parameter is the same as the create method we used in the previous example.

let particleStream = d.emitter(
 100, () => d.create(); ) ;Copy the code

Any interval value of 100 milliseconds or less will make the particles appear to flow in a continuous stream. Here is some code to generate the star fountain effect.

let particleStream = d.emitter(
                100,
                () => d.create(
                    128.128,
                    () => su.sprite(imgURL),
                    stage,
                    30.0.1.false.3.14.6.28.30.60.1.5));Copy the code

The sixth parameter, 0.1, is gravity. Set gravity to a higher number and the particle will fall faster. The Angle is between 3.14 and 6.28. This causes the particle to appear within an Angle of the size of the half moon above its origin. The following figure shows how to define this Angle.

The star is created at the central origin and then flies up in the upper half of the circle. However, the stars will eventually fall to the bottom of the canvas due to gravity, which is how the star-shaped fountain effect is created.

You can turn the flow of particles on and off at any time in code using The Play and Stop methods emitter, as shown below:

particleStream.play();
particleStream.stop();
Copy the code

Effect:

Complete code:


      
<html lang="zn">

<head>
    <meta charset="UTF-8">
</head>

<body>
    <div id="px-render"></div>

    <script src="https://www.kkkk1000.com/js/pixi4.8.2.js"></script>
    <script src="https://www.kkkk1000.com/js/spriteUtilities.js"></script>
    <script src="https://www.kkkk1000.com/js/dust.js"></script>
    <script>
        // Some parameters needed to create a Pixi application
        let option = {
            width: 400.height: 300.transparent: true,}// Create a Pixi application
        let app = new PIXI.Application(option);
        // Get the stage
        let stage = app.stage;
        // Get the renderer
        let renderer = app.renderer;
        let playground = document.getElementById('px-render');
        // Add the canvas created by Pixi to the page
        playground.appendChild(renderer.view);

        let su = new SpriteUtilities(PIXI);
        let d = new Dust(PIXI);
        let particleStream;

        // The address of the image to load
        let imgURL = "https://www.kkkk1000.com/images/learnPixiJS-ParticleEffects/star.png";
        // Load the image, and then execute the setup function
        PIXI.loader.add(imgURL).load(setup);

        function setup() {
            let particleStream = d.emitter(
                100,
                () => d.create(
                    128.128,
                    () => su.sprite(imgURL),
                    stage,
                    30.0.1.false.3.14.6.28.30.60.1.5)); particleStream.play();// Start the game loop
            gameLoop();
        }

        function gameLoop() {
            requestAnimationFrame(gameLoop);
            d.update();
            renderer.render(stage);
        }
    </script>
</body>

</html>
Copy the code

See the effect

PixiJS – Sprite state

Next, learn about PixiJS – Visual effects