Jump to content

Reuse animations


kurhlaa
 Share

Recommended Posts

Hi,

From this example - https://github.com/robhimslf/game-dev-invaders - I try to use bullets explosion animation. If I understand it right - author has created a group of 30 animations and is using them one by one. Here are the main parts:

...
// This is a collection of explosions.
var explosions;
...
// Preload the explosion image.
this.load.spritesheet( 'kaboom', 'explode.png', {
    frameWidth: 128,
    frameHeight: 128
});
...
// Setup our explosion animation.
this.anims.create({
    key: 'explode',
    frames: this.anims.generateFrameNumbers( 'kaboom', {
        start: 0,
        end: 15
    }),
    frameRate: 16,
    repeat: 0,
    hideOnComplete: true
});
...
// Create some explosions!
explosions = this.add.group({
    defaultKey: 'kaboom',
    maxSize: 30
});
...

and here is what's happening at the bullet's collision time:

...
// Get the first explosion, and activate it.
var explosion = explosions.get().setActive( true );

// Place the explosion on the screen, and play the animation.
explosion.setOrigin( 0.5, 0.5 );
explosion.x = target.x;
explosion.y = target.y;
explosion.play( 'explode' );
...

However, if you launch animations more than 30 times (try to shoot all the targets) - there is a JS error:

Uncaught TypeError: Cannot read property 'setActive' of null
    at handleCollision (invaders.js:391)
    at Function.handlePlayerCollision (invaders.js:408)
    at initialize.collideSpriteVsSprite (phaser.min.js:1)
    at initialize.collideHandler (phaser.min.js:1)
    at initialize.collideObjects (phaser.min.js:1)
    at initialize.update (phaser.min.js:1)
    at initialize.step (phaser.min.js:1)
    at initialize.update (phaser.min.js:1)
    at initialize.h.emit (phaser.min.js:1)
    at initialize.step (phaser.min.js:1)

Line 391 is:

var explosion = explosions.get().setActive( true );

 

If I understand it right - animations are not being reused. So after calling get() 30 times - no free animations left. How this can be fixed?

Link to comment
Share on other sites

@aylictal, with destroy() I get the same error at some moment. Maybe you wanted to say to destroy if I do NOT need it after the explosion? Because in my case I reuse existing sprites animations. It was written somewhere that it's expensive to create new objects all the time, so it's preferable to reuse them.

Link to comment
Share on other sites

Depends by what you mean expensive.

Destroy allows garbage collection to occur for it, so that it requires less in memory.  Memory has always been my main constraint with my personal projects because my scenes are always so big, but to each their own.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...