扩展Phaser.js类

时间:2015-03-24 11:22:02

标签: javascript oop phaser-framework

我正在使用Phaser框架,我想创建一个新的类来保存phaser中精灵类的所有属性,所以我试着这样做

var mario = function(){

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

但是有一个错误“Uncaught TypeError:undefined不是函数”

然后我试了

var mario = function(){

   this.anything = "";

};

mario.prototype = new Phaser.Sprite();

确定它有效,但它调用了相位器构造函数,我不想创建精灵,直到我做var heroObj = new mario();

我该怎么办?

3 个答案:

答案 0 :(得分:5)

现在使用ES6会更容易,例如:

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
    }
}

然后您可以像这样导入和使用它:

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

这是一个可以帮助您入门的样板:https://github.com/belohlavek/phaser-es6-boilerplate/

答案 1 :(得分:4)

试试这样。我添加了一个命名空间来避免全局变量。

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';
    ...
};

然后你可以实例化它:

var mario = new YourGameNSpace.Mario(game);

答案 2 :(得分:1)

我编写了一小组JS实用程序,包括继承(可能甚至是抽象)类:

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() {
        // ...
    }
});

如果您有兴趣,you can see the result of applying it to Phaser's "Sprite Demo 2" in this fiddle