Jump to content

Destroying instances


badaf
 Share

Recommended Posts

Hi all,

I'm working on my first Phaser based game, online documentaion is very useful, but I can't find informations about destroying instances.

function Enemy(game, layer, x, y, enemyStyle){
    var newX = 0;
    var newY = 0;
    
    switch(enemyStyle){
        case 'big_guy':
            newX = x;
            newY = y-68;
            break;
        case 'fast_guy':
            newX = x;
            newY = y-24;
            break;
    }

    var mySprite = game.add.sprite(newX, newY, decoType);
    mySprite.anchor.setTo(0.5, 0.5);
    layer.add(mySprite);
}

Enemy.prototype.delete = function(){
    mySprite.destroy();
}

Here I can destroy the enemy sprite, but not the enemy instance..

Link to comment
Share on other sites

function Enemy(game, layer, x, y, enemyStyle){
    // …

    this.mySprite = game.add.sprite(newX, newY, decoType);
    this.mySprite.anchor.setTo(0.5, 0.5);
    layer.add(this.mySprite);
}

Enemy.prototype.delete = function(){
    this.mySprite.destroy();
    this.mySprite = null;
}

There's no need to destroy the Enemy instance (and really there's no such concept in JS). It will eventually pass into oblivion if you no longer reference it.

Link to comment
Share on other sites

Thanks, it's difficult to understand these "JS concepts" coming from other oop languages...

Another question :

if I want to restart my game (destroy all sprites, reset all variables, clear screen, like user pressed F5 :) ), can I do something like this ?

// launch the game 1st time
this.myGame = new Game();

// delete
this.myGame.destroy();

// launch new game
this.myGame = new Game();

 

Link to comment
Share on other sites

If Game is Phaser.Game then that should probably work.

But usually you don't need to throw out everything, you can just do

game.state.restart(); // or `this.state.restart()` within a state callback

That will stop the current state, empty the world, and then start the state again.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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