我使用Phaser框架,我想创建新的类,在phaser中保存sprite类的所有属性,所以我尝试这样做。
var mario = function(){
Phaser.Sprite.call(this); // inherit from sprite
};但是有一个错误“未定义的TypeError:未定义的不是函数”
然后我试着
var mario = function(){
this.anything = "";
};
mario.prototype = new Phaser.Sprite();好的,它工作,但它称为相位构造函数,我不想创建雪碧,直到我做var heroObj = new mario();
我该怎么办?
发布于 2015-03-24 11:43:21
像这样试试。我添加了一个名称空间以避免全局变量。
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);发布于 2016-02-26 15:21:55
例如,对于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/
发布于 2016-03-19 06:16:39
我编写了一小部分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() {
// ...
}
});如果你感兴趣,你可以看到把它应用到Phaser的“雪碧演示2”中的效果。。
https://stackoverflow.com/questions/29231281
复制相似问题