Search code examples
timerphaser-frameworkphaserjs

Phaser timer activated events. How?


I'm trying to make a game where certain things happen based on a timer that keeps going up. For example, certain text, images, or clickable buttons only appear after a certain amount of time has passed on a specific screen. Or maybe an image briefly flashes onto the screen when the timer equals certain numbers.

Unfortunately, I have got no clue how to make this happen. Can anyone show me a solution? Examples are perfered.

If it helps, I'm using Phaser 3 in VSCode.


Solution

  • I sugest checking out the time documentation, or the time examples on the official homepage.

    Basically you just need to use this.time.addEvent( ... );

    UPDATED Herer a short demo:

    document.body.style = 'margin:0;';
    
    var config = {
        type: Phaser.AUTO,
        width: 536,
        height: 183,
        scene: {
            create,
            update
        }
    }; 
    
    function create () {
        this.label1 = this.add.text(50, 50, 'Timer: 0')
            .setScale(2.5)
            .setOrigin(0)
            .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});
            
        this.label2 = this.add.text(50, 100, 'Update Timer: 0')
            .setScale(2.5)
            .setOrigin(0)
            .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});
        
        this.currentAppTime = 0;
      
        let counter = 1;
      
        this.time.addEvent({
            delay: 1500, 
            callback: () => this.label1.setText(`Timer: ${counter++}` ),
            callbackScope: this, 
            loop: true 
        });
    }
    
    function update(time, delta){
        let helperTime = Math.floor(time / 1000);
        if(helperTime > this.currentAppTime){
            this.currentAppTime = helperTime;
            this.label2.setText(`Update Timer: ${this.currentAppTime}` )
        }
    }
    
    new Phaser.Game(config);
    <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>