我正在尝试制作一个简单的JavaScript游戏。在游戏中,所有游戏对象都应该能够被拖放。现在,这段代码可以解决问题:
function create() {
game.stage.backgroundColor = 'rgba(255, 255, 255, 0.5)'
combinator = game.add.sprite(10, 15, 'Combinator')
comparer = game.add.sprite(100, 15, 'Comparer')
button = game.add.sprite(50, 15, 'Button')
button.inputEnabled = true;
button.input.enableDrag(true);
combinator.inputEnabled = true;
combinator.input.enableDrag(true);
comparer.inputEnabled = true;
comparer.input.enableDrag(true);
}
但是我试图为所有gameObjects创建一个类,其中inputEnabled = true和input.enableDrag(true),所以我只需要定义一次。我认为这样的事情是这样的:
class gameObject {
constructor () {
this.inputEnabled = true;
this.input.enableDrag(true);
}
}
但我无法理解如何在create函数中使用它。我是否需要将game.add.sprite(x,y,' name')作为课程的一部分?
答案 0 :(得分:1)
您可以创建一个为您创建精灵的工厂类。
class SpriteFactory {
constructor(game) {
this.game = game
}
getDraggableSprite(...spriteParameters) {
const sprite = this.game.add.sprite(...spriteParameters)
sprite.inputEnabled = true
sprite.input.enableDrag(true)
return sprite
}
}
function create() {
game.stage.backgroundColor = 'rgba(255, 255, 255, 0.5)'
const spriteFactory = new SpriteFactory(game)
combinator = spriteFactory.getDraggableSprite(10, 15, 'Combinator')
comparer = spriteFactory.getDraggableSprite(100, 15, 'Comparer')
button = spriteFactory.getDraggableSprite(50, 15, 'Button')
}