Reputation: 1018
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 ?
Upvotes: 4
Views: 5019
Reputation: 73984
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´s a boilerplate to get you started: https://github.com/belohlavek/phaser-es6-boilerplate/
Upvotes: 6
Reputation: 24528
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.
Upvotes: 1
Reputation: 2113
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);
Upvotes: 6