简体   繁体   中英

extending Phaser.js classes

im working with Phaser framework , i want to create new class that hold all properties from sprite class in phaser so i tried doing this

var mario = function(){

    Phaser.Sprite.call(this); // inherit from sprite
};

but there was an error "Uncaught TypeError: undefined is not a function"

then i tried

var mario = function(){

   this.anything = "";

};

mario.prototype = new Phaser.Sprite();

OK it works but it called phaser constructor and i don't want to create sprite until i do var heroObj = new mario();

what should i do ?

Try like this. I added a namespace to avoid global variables.

var YourGameNSpace = YourGameNSpace || {};

YourGameNSpace.Mario = function (game) {
    'use strict';

    Phaser.Sprite.call(this, game);
};

// add a new object Phaser.Sprite as prototype of Mario 
YourGameNSpace.Mario.prototype = Object.create(Phaser.Sprite.prototype);
// specify the constructor
YourGameNSpace.Mario.constructor = YourGameNSpace.Mario;

//add new method
YourGameNSpace.Mario.prototype.init = function () {
    'use strict';
    ...
};

And after you can instantiate it:

var mario = new YourGameNSpace.Mario(game);

This is much easier now with ES6, for example:

export default class CustomSprite extends Phaser.Sprite {
    constructor(game){
        super(game, 0, 0);
        this.addChild(game.add.sprite(0, 0, 'someSprite'));
        game.stage.addChild(this);
    }
    update() {
        //move/rotate sprite
    }
}

You can then import and use it like this:

this.customSprite = new CustomSprite(this.game);
this.customSprite.x = 400;
this.customSprite.y = 100;

Here´sa boilerplate to get you started: https://github.com/belohlavek/phaser-es6-boilerplate/

I wrote a small set of JS utilities, including inheritance with (potentially even abstract) classes:

var Unit = squishy.extendClass(Phaser.Sprite, 
function (game, x, y, sprite, ...) {
    // ctor

    // Call the the base (Sprite) ctor
    this._super(game, x, y, sprite);

    // ...
},{
    // methods
    update: function() {
        // ...
    }
});

If you are interested, you can see the result of applying it to Phaser's "Sprite Demo 2" in this fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM