绿岛之北

好读书,不求甚解;每有会意,便记下笔记。

导航

[PhaserJS] 鼠标事件

鼠标事件

要想监听事件,需要先调用GameObject的setInteractive方法,该方法会将GameObject传给输入管理器,以便可以响应输入。

GameObject继承自EventEmitter(eventemitter3),因此具体标准的事件处理方法

事件管理

事件方法 描述
on(event, fn [, context]) 新增事件
off(event [, fn] [, context] [, once]) 取消事件
once(event, fn [, context]) 增加一个单次事件
emit(event [, args]) 触发事件
addListener(event, fn [, context]) 新增事件
removeListener(event [, fn] [, context] [, once]) 取消单个事件
removeAllListeners( [event]) 取消所有事件

鼠标事件列表

事件名 描述
pointerdown 鼠标按下
pointerup 鼠标抬起
pointermove 鼠标在游戏对象上移动
pointerout 鼠标移出游戏对象
pointerover 鼠标移入游戏对象
wheel 鼠标在游戏对象上滑动滚轮

简单示例

const star = this.add.star(250, 150, 5, 32, 64, 0xff0000, 1);
star.setInteractive();
star.on('pointerup', () => {
  console.log('鼠标抬起事件');
});

完整示例

class SceneA extends Phaser.Scene {
    constructor() {
        super({
            key: 'SceneA'
        });
    }

    create() {
        const star = this.add.star(250, 150, 5, 32, 64, 0xff0000, 1);
        const text = this.add.text(160, 140, '状态', {
            fixedWidth: 180,
            align: 'center'
        });
        star.setInteractive();
        star.on('pointerdown', () => {
            text.setText('鼠标按下');
        }, this);
        star.on('pointerup', () => {
            text.setText('鼠标抬起');
        }, this);
        star.on('pointermove', () => {
            text.setText('鼠标移动' + Math.floor(Math.random() * 100));
        }, this);
        star.on('pointerout', () => {
            text.setText('鼠标移出');
        }, this);
        star.on('pointerover', () => {
            text.setText('鼠标移入');
        }, this);
        star.on('wheel', () => {
            text.setText('滚轮滚动' + Math.floor(Math.random() * 100));
        }, this);
    }
}

new Phaser.Game({
    width: 500,
    height: 300,
    scene: [SceneA]
});

在线体验

posted on 2022-05-31 14:18  绿岛之北  阅读(165)  评论(0编辑  收藏  举报