Jump to content

Adding methods to a Scene without extending it


fariazz
 Share

Recommended Posts

Hi all,

I'm trying to build a demo keeping it simple with ES5, and I'm trying to add a custom method to a scene, in a way similar to how it was done on Phaser 2. I realized this is not possible and was wondering if there is any recommended way to do this (without using ES6 to extend the Scene class, and without adding functions in the global scope either):

var GameScene = {
  preload: ...
  
  create: ...

  update: function() {
   
    // custom logic

    
    if(...) {
       // if something happens, game over (doesn't work). this.gameOver is undefined
       this.time.delayedCall(500, this.gameOver, [], this);
    }
     
  },

  // adding this custom method like in Phaser 2 - doesn't work on Phaser 3
  gameOver: function() {
    console.log("game over");
  }
}

var config = {
  type: Phaser.AUTO,
  width: 640,
  height: 360,
  scene: GameScene
};

var game = new Phaser.Game(config);

 

Link to comment
Share on other sites

I kind of found my answer already in the scene examples in case it helps anyone.

Instead of creating the scene as an object like above, the way presented in the example seems much better for ES5. More examples are available there as well:

var gameScene = new Phaser.Scene('Game');

gameScene.myMethod = function() {
  console.log('yo');
};

// load asset files for our game
gameScene.create = function() {

  console.log(this.myMethod);
};

 

Link to comment
Share on other sites

  • 2 months later...
 Share

  • Recently Browsing   0 members

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