Jump to content

cleanly destroying a custom gameobject


jasper1990
 Share

Recommended Posts

I have a dialogue box object that I custom made for an adventure/shooter game. In the code below, the custom object has a graphic component to draw a black background. when I use the  "destroy" method, only the text goes away.  thank you for any help

 

var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    parent: 'phaser-example',
    backgroundColor:'#ffffff',
    scene: {
        create: create,
        update: update
    }
};

var game = new Phaser.Game(config);
var dialogue;
//var timerEvent;
//var count = 0;

//var str = "this is the test string that will be used for this demo";

class DialogueBox extends Phaser.GameObjects.Text {
    constructor(params){
        super(params.scene, params.x + 10, params.y + 10, '', params.style);
        this.setDepth(1);
        this.graphics = params.scene.add.graphics();
        this.graphics.fillStyle(0, 1);
        this.graphics.fillRect(params.x, params.y, 1000, 200);
        this.strcontent = params.text;
        this.timerEvent = params.scene.time.addEvent({ delay: 50, repeat: params.text.length });
        this.count = 0;
        params.scene.add.existing(this);
    }

    update(){
        this.renderText(this.timerEvent.getProgress());
    }

    renderText(progress){
        if(progress > 0.98){
            this.setText(this.strcontent.substring(0,this.count));
            this.count += 1;
        }
    }
}


function create() 
{

    //  Pass in a basic style object with the constructor
    //dialogue = this.add.text(10, 200, ' ', { fontFamily: 'Arial', fontSize: 16, color: '#ffffff' }).setDepth(1);

    //timerEvent = this.time.addEvent({ delay: 50, repeat: str.length });

    dialogue = new  DialogueBox({scene: this, x: 0, y: 200, text:"this is the test string that will be used for this demo", style:{ fontFamily: 'Arial', fontSize: 16, color: '#ffffff' }});
    this.input.keyboard.on('keydown', function (event) {
        dialogue.destroy();
    });
}

function update(){
    //enderText(timerEvent.getProgress());
    dialogue.update();
}

/*function renderText(progress){
    if(progress > 0.98){
        dialogue.setText(str.substring(0,count));
        ++count;
    }
}*/

 

Link to comment
Share on other sites

In Phaser 3 only Containers can contain other game objects, so in this case you are adding your graphics separately to the scene. When you call destroy(), only the text object is destroyed and the graphics remains as it is not "connected" to the text object. You could put both inside a container and then destroy container and it should destroy both text and graphics. Since you don't have many objects to put into container in this case, I think you should avoid it and just call another destroy on the graphics.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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