azerion / phaser-input

Adds input boxes to Phaser like CanvasInput, but also works for WebGL and Mobile, made for Phaser only.
MIT License
201 stars 64 forks source link

Usage with TypeScript #53

Closed tommitytom closed 6 years ago

tommitytom commented 6 years ago

Hi folks, I've been tinkering with this plugin today using TypeScript, phaser-ce v2.8.0, using gulp as my build manager. I encountered a few issues along the way and thought I would detail my process, and/or see if there is a better way of doing this.

Accessing the module globally

Firstly I had to get the TypeScript compiler to make use of the definitions, as the PhaserInput module was not available to me. To do this, I:

  1. Created node_modules/@orange-games/phaser-input/build/typings.json which contains:

    {
    "name": "phaser-input",
    "main": "phaser-input.d.ts",
    "global": true
    }
  2. Modified ./typings.json, to add a phaser-input field to globalDevDependencies. The file now contains:

    {
    "globalDevDependencies": {
        "phaser": "file:node_modules/phaser-ce/typescript/typings.json",
        "phaser-input": "file:node_modules/@orange-games/phaser-input/build/typings.json"
    }
    }
  3. Ran typings install in the project root directory

This allowed me to access the PhaserInput module globally.

Adding the plugin

Next up I was unable to add the plugin to the game, as I was getting this error:

Argument of type 'typeof Plugin' is not assignable to parameter of type 'Plugin'. Property 'active' is missing in type 'typeof Plugin'.

After a browse at some other plugins, I notice they use this method (which also works in this case)

this.game.add.plugin(new PhaserInput.Plugin(this.game, this.game.plugins));

Gaining access to game.add.inputField()

When trying to use the game.add.inputField() method I was getting the following error:

Property 'inputField' does not exist on type 'GameObjectFactory'.

To fix this I added the following member variable to the Phaser.State I am creating

export default class Menu extends Phaser.State {
    public game: PhaserInput.InputFieldGame; // Added

    public create() {
        const input = this.game.add.inputField(10, 10);
        // etc...
    }
}
AleBles commented 6 years ago

Hey man, thanks for the awesome write-up, as for your points:

1) I put all my external references in a file in the project, as seen here: https://github.com/orange-games/phaser-ts-boilerplate/blob/master/ts/definitions.d.ts

This way I'm not dependant on external projects having typings or not

2) Hmm, I still mostly work on Phaser 2.6.2, so that might be a change in the -ce addition. I don't test my plugins on the ce version, but I'll add this info to the readme

3) I usually use something similar like that, but since I user more plugins I overwrite the entire game object as per: https://github.com/orange-games/phaser-ts-boilerplate/blob/master/ts/Fabrique/IGame.ts