如何在Phaser 3中创建动画按钮?

时间:2019-04-11 17:02:00

标签: phaser-framework

首先,我正在使用Phaser3。我想在Spritesheet中创建一个按钮。当鼠标悬停按钮时,我希望第二帧在鼠标离开时出现并消失。

this.load.spritesheet('button', 'static/img/button.png', {frameWidth: 191, frameHeight: 71})

(这只是一张2帧的图像)

我被卡住了,因为找不到相位器3按钮上的任何文档,原因显然是它们不存在。这全都与图像或文本上的事件有关。那么这里的方法是什么?

2 个答案:

答案 0 :(得分:1)

您将要像这样将精灵创建为按钮:

this.add.sprite(100, 100, 'button').setFrame([frame name/number]).setInteractive();

这将创建一个交互式GameObject,并以您的按钮作为图像。框架名称/编号将从您的Spritesheet中的第一张图像开始。它开始从0开始计数帧,因此您可能首先要从0开始。

然后,您需要使用this example之类的鼠标事件来更改悬停时的帧。

类似的东西:

// When hovering
this.input.on('pointerover', function(e, button) {
  button.setFrame(1);
});

// When moves away
this.input.on('pointerout', function(e, button) {
  button.setFrame(0);
});

答案 1 :(得分:0)

我在github上放了一个Phaser3 example game,它向场景添加了一个Button原型,并且按钮的工作方式类似于Phaser v2

// add a button to a scene
// similar to buttons in Phaser v2
Phaser.Scene.prototype.addButton = function(x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame)
{
        // add a button
        var btn = this.add.sprite(x, y, key, outFrame).setInteractive();
        btn.on('pointerover', function (ptr, x, y) { this.setFrame(overFrame) } );
        btn.on('pointerout',  function (ptr)       { this.setFrame(outFrame) } );
        btn.on('pointerdown', function (ptr)       { this.setScale(0.9, 0.9) } );
        btn.on('pointerup', callback.bind(callbackContext));

        return btn;
};

// load sprite sheet
this.load.atlas('sprites', 'img/mysprites.png', 'img/mysprites.json');

// then use it like this
this.btnback = this.addButton(100, 100, 'sprites', this.myBtnCallBack, this, 'btn_back_hl', 'btn_back', 'btn_back_hl', 'btn_back');
相关问题