Jump to content

ES6 Class Usage Example


christiansakai
 Share

Recommended Posts

Hello, new to this forum! I have a question regarding ES6 Class usage in Phaser.

So I have a Diver (sprite) class and the Main (state) class. I am using the two classes like this
 

class Diver extends Phaser.Sprite {
  constructor(game, coordinateX, coordinateY, key) {
    super(game, coordinateX, coordinateY, key);

    this.game.add.sprite(coordinateX, coordinateY, key);
  }
}

export default Diver;

 

import Diver from "../objects/Diver";

class Main extends Phaser.State {
  init() {}

  preload() {
    this.game.load.image("diver", "/public/images/diver.png");
  }

  create() {
    const diver = new Diver(this.game, 200, 200, "diver");
  }

  update() {}
}

export default Main;

 

Is this approach above the best way to do this? Seems that it is not as encapsulated as I thought it will be.

1. What if I want to put the `game.load.image` inside the Diver class?

2. I am adding the Diver to the Main by using `this.game.add.sprite` method inside the Diver's constructor. Seems odd to me or it isn't? What if I want to do this inside Main class and not inside Diver class?

 

Thanks for the help!

Link to comment
Share on other sites

  • 1 month later...

A little late reply but...

I would probably add the load.image() to the Diver constructor to be created in Main.preload() and later have a Diver.create() called in the Main.create() method. This way in Diver.create() you can also attach any sound effects or key bindings and reset any stats for each Diver.

And lastly in the Main.update() call a Diver.update() that controls this Diver's position and animation so it's not controlled by individual methods called in Main.update()

Only expose the minimal methods from Diver that would be useful outside of the Diver object.

Link to comment
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...
 Share

  • Recently Browsing   0 members

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