fariazz

Adding methods to a Scene without extending it

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);

 

Share this post


Link to post
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);
};

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.