Sign in to follow this  
badaf

Destroying instances

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..

Share this post


Link to post
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.

Share this post


Link to post
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();

 

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.