Timer not working inside function in Phaser 3

2019-08-17 18:27发布

问题:

I have a spawn function which performs some task. Before the function returns, I would like to delay some another function call.

I tried using time.addEvent but with no luck as it does not seem to work within the spawn function. However the timer works perfectly inside the create function.

My code so far:

create(){
  newMethod = spawn.bind(this);
  newMethod();
}

function spawn(){
  //do stuff
  timer = this.time.addEvent({
    delay: 3000,
    callback: functionDelay,
    loop: false
  });
}

function functionDelay(){
  console.log("Works!");
}

回答1:

var delayText;
var delayedEvent;

class myScene extends Phaser.Scene {

    constructor (config)
    {
      super(config);
    }

    preload ()
    {
      this.load.image('dude', 'sprites/phaser-dude.png')
    }
   
    create () 
    {
      delayText = this.add.text(50, 50);
      delayedEvent = this.time.delayedCall(3000, this.spawn, [], this);
    }
    
    spawn()
    {
      var sprite = this.add.sprite(300, 50, 'dude')
    }
    
    update()
    {
      delayText.setText('Event.progress: ' + delayedEvent.getProgress().toString().substr(0, 4));
    }
}

var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://cdn.jsdelivr.net/gh/samme/phaser-examples-assets@v2.0.0/assets/',
      crossOrigin: 'anonymous'
    },
    width: 800,
    height: 600
};

var game = new Phaser.Game(config);

game.scene.add('myScene', myScene, true);
<script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script>