Home > Software engineering >  Trying to loop Phaser 3 scene only specific time
Trying to loop Phaser 3 scene only specific time

Time:06-27

for (var i = 0; i < 5; i  ) {
  this.time.addEvent({
    delay: 300,
    loop: false,
    callback: () => {
      this.scene.start("scene1");
    }
  })
}

Here is my another scene, I am trying to loop the scene back to scene 1 only for specific time but the for loop do not work. It still loop the scene infinitely. What should I do?

CodePudding user response:

The problem is, that you are are calling the time event multiple times, in the for- loop, and you can only call start once on the same scene.

This causes an Error, when the time event is executed the second time (asynchronous). Since the function start shutdowns the current scene = this(details in the documentation).

Why are you calling it multiple times this.scene.start("scene1"); in the for-loop? This doesn't make sense.

Update:
(Just a small demo showing automatic switching)

  let SCENES_KEYS = ['SceneOne', 'SceneTwo', 'SceneThree'];
  let current_scene_index = 0;

  class SceneTimeSwitcher extends Phaser.Scene {
    constructor (config) {
        super(config);
    }

    create () {
        this.time.addEvent({
            delay: 1000,
            loop: false,
            callback: () => {
                current_scene_index  ;
                if(current_scene_index >= SCENES_KEYS.length){
                    current_scene_index = 0;
                }
                this.scene.start(SCENES_KEYS[current_scene_index]);
            }
        })
    }
}


class SceneOne extends SceneTimeSwitcher {
    constructor (config) {
        super('SceneOne');
    }

    create () {
        super.create();
        this.add.text(20,20, 'SCENE ONE');
    }
}

class SceneTwo extends SceneTimeSwitcher {
    constructor (config) {
        super('SceneTwo');
    }

    create () {
        super.create();
        this.add.text(20,20, 'SCENE TWO');
    }
}

class SceneThree extends SceneTimeSwitcher {
    constructor (config) {
        super('SceneThree');
    }

    create () {
        super.create();
        this.add.text(20,20, 'SCENE THREE');
    }
}

var config = {
    type: Phaser.AUTO,
    width: 536,
    height: 183,
    scene: [ SceneOne, SceneTwo, SceneThree ]
};

new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>

  • Related