Jump to content

Phaser Destroy GameObjects


Pave
 Share

Recommended Posts

After certain game actions I want to remove some Sprites.

Currently I am using:

this.destroy();

But this doesn''t stop the execution of the currently running "preUpdate" function. So my game crashes, because the object doesn't exist anymore but the code continues to run till the end of the preUpdate and then stops.

Is there a solution for this?

I don't want to use "disableBody" or something like that, because I want the Garbage Collector to pick up the sprite.

Link to comment
Share on other sites

The Class:

class Enemy extends Phaser.Physics.Arcade.Sprite {

	constructor (scene, x,y)
    {
        super(scene, x,y);
    }
	
    preUpdate (time, delta)
    {
        super.preUpdate(time, delta);
    }
    
    destroyEnemy(){
       this.destroy();
    }
}

class Enemy1 extends Enemy {

    constructor (scene, x, y)
    {
        super(scene, x, y);
    }

    preUpdate (time, delta)
    {
        super.preUpdate(time, delta);
        if(this.y > 300){
            this.setVelocityY(this.body.velocity.y*-1);
        }
    }
}

In the scene:

var config = {
    type: Phaser.AUTO,
    width: gameWidth,
    height: gameHeight,
    parent: 'game',
    resolution: window.devicePixelRatio || 1,
    physics: {
        default: 'arcade',
        arcade: {
            debug: true
        }
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

    var game = new Phaser.Game(config);


    function create ()
    {
        // Add Groups
        Bullet.bullets = this.physics.add.group();
        Enemy.enemies = this.physics.add.group();
        
        // Check if bullet overlaps with enemy
        this.physics.add.overlap(Enemy.enemies, Bullet.bullets, enemyHit, null, this);
    }

    function enemyHit (enemy, bullet)
    {
        // Remove the enemy
        enemy.destroyEnemy();
        
        // Remove the Bullet
        bullet.destroyBullet();
        
    }

 

After the collision the Enemy gets destroyed. But the game crashes when it tries to set the velocity of the non existing enemy.

Edited by Pave
Link to comment
Share on other sites

  • 2 years later...
 Share

  • Recently Browsing   0 members

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