Hiero
Hiero

Reputation: 2205

Pixi.js draw falling squares

I drawed a grid based system on canvas using PIXI.js.

I'm trying to animate the thing, first each particle position.y is -200, then using Tween.js I'm trying to make them fall.

I change the position to the correct position, which is particle._y.

As you notice you will see after falling there are some empty spaces and CPU is over heating.

http://jsbin.com/wojosopibe/1/edit?html,js,output

function animateParticles() {
    for (var k = 0; k < STAGE.children.length; k++) {

        var square = STAGE.children[k];
        new Tween(square, 'position.y', square._y, Math.floor(Math.random() * 80), true);

    }
}

I think I'm doing something wrong.

Can someone please explain me what I'm doing wrong and why there are some empty spaces after falling?

Upvotes: 2

Views: 1857

Answers (1)

Karmacon
Karmacon

Reputation: 3190

The reason for the empty spaces is that some of your animations are not starting. The cause is in this line:

new Tween(square, 'position.y', square._y, Math.floor(Math.random() * 80), true);

Looking at your function definition for Tween.js, I see this:

function Tween(object, property, value, frames, autostart)

The fourth parameter is frames. I'm assuming this is the number of frames required to complete the animation. Well your Math.floor function willl sometimes return zero, meaning the animation will have no frames and won't start!!

You can fix this by using math.ceil() instead. This way there will always be at least 1 frame for the animation:

new Tween(square, 'position.y', square._y, Math.ceil(Math.random() * 80), true);

Now, as for performance, I would suggest setting this up differently...

Animating all those graphics objects is very intensive. My suggestion would be to draw a single red square, and then use a RenderTexture to generate a bitmap from the square. Then you can add Sprites to the stage, which perform WAY better when animating.

//Cretae a single graphics object
var g = new PIXI.Graphics();
g.beginFill(0xFF0000).drawRect(0, 0, 2, 2).endFill();

//Render the graphics into a Texture
var renderTexture = new PIXI.RenderTexture(RENDERER, RENDERER.width, RENDERER.height);
renderTexture.render(g);

for (var i = 0; i < CONFIG.rows; i++) {
    for (var j = 0; j < CONFIG.cols; j++) {

        var x = j * 4;
        var y = i * 4;

        //Add Sprites to the stage instead of Graphics
        var PARTICLE = new PIXI.Sprite(renderTexture);
        PARTICLE.x = x;
        PARTICLE.y = -200;

        PARTICLE._y = H - y;

        STAGE.addChild(PARTICLE);
    }
}

This link will have some more examples of a RenderTexture: http://pixijs.github.io/examples/index.html?s=demos&f=render-texture-demo.js&title=RenderTexture

Upvotes: 1

Related Questions