Sky*_*ker 4 javascript oop phaser-framework
我正在使用Phaser框架,我想创建一个新的类,在phaser中保存sprite类的所有属性,所以我尝试这样做
var mario = function(){
Phaser.Sprite.call(this); // inherit from sprite
};
Run Code Online (Sandbox Code Playgroud)
但是有一个错误"Uncaught TypeError:undefined is not a function"
然后我试过了
var mario = function(){
this.anything = "";
};
mario.prototype = new Phaser.Sprite();
Run Code Online (Sandbox Code Playgroud)
确定它有效,但它调用了相位器构造函数,我不想创建精灵,直到我这样做 var heroObj = new mario();
我该怎么办 ?
尝试这样。我添加了一个命名空间以避免全局变量。
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';
...
};
Run Code Online (Sandbox Code Playgroud)
然后可以实例化它:
var mario = new YourGameNSpace.Mario(game);
Run Code Online (Sandbox Code Playgroud)
现在使用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
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以像这样导入和使用它:
this.customSprite = new CustomSprite(this.game);
this.customSprite.x = 400;
this.customSprite.y = 100;
Run Code Online (Sandbox Code Playgroud)
这是一个可以帮助您入门的样板:https://github.com/belohlavek/phaser-es6-boilerplate/
| 归档时间: |
|
| 查看次数: |
4042 次 |
| 最近记录: |