Jump to content

Proper way to reference a class constructor from another scene?


Lukripar
 Share

Recommended Posts

I have a class Player.js that handles the creation of my player, and I have game.js which is where I run my game. What is the correct way in the game.js to call the Player class?

 

for example:

let player;

class Game extends Phaser.Scene{

...

create(){

player = this.add.sprite(400,400,'dude');

this.player = new Player(this);

}

my assets are handled in a preload scene. The italics portion is what I'm having problems with. It keeps saying Player is not defined.

if I try to import it into the game.js file, I get an unexpected token error.

 

Thank you for your help.

 

Link to comment
Share on other sites

Since I had the same issues a couple of days ago, here is what I found out: (not sure I got everything correct, but it may help you) 

With nativ Javascript (with compatibility for all browsers) there is no such thing as an import, so you ether push all classes in one file in the correct order, add the files in the correct order to your index.html or (probably the best way) use some transpiler that does the magic for you.

If you happen to have such a transpiler setup up and running, the exact syntax depends on that setup. 

With ES6 (and Bable) you would write something like 

import { Player } from "player";

With typescript the Syntax would be similar but you need to add `export` to your Player.js file, i.e.

// player.js
export class Player { ... }

// game.js
import { Player } from "player";

Node.js uses a require Function, but I'm not quite sure what the syntax is. It's something like

var player = require('player');
// ...
player = new player.Player(this);

In case you just use plain javascript, I would advise you to setup a toolchain, that does manage the complicated stuff for you. For Phaser3 you may take one of the templates from here, there is support for ES6, TypeScript and Coffescript, with live reload and deployment. It's very easy to setup and your project gets a lot more structured.

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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