首页 文章

Phaser,使按钮单击事件连续

提问于
浏览
0

我正在使用Phaser.js来创建一个 Map (tileSprite),并在其上有一些精灵,因为不是所有的精灵都可以进入,我正在使用相机左右平移 .

我希望用户单击键盘键(左或右)或方向按钮精灵来连续平移相机,直到用户释放控件 .

我实现了类似于this example的键盘平移,我按住一个键,相机移动/平移(事件的每一边10个像素),并在按键释放时停止 .

但是,当我尝试使用2个精灵按钮实现相同的功能时,每个按钮仅触发1个事件并且每次点击仅平移10个像素 . 我需要继续射击直到我放开钥匙 .

var panRightButton = game.add.button(800, 5, 'right_pan_btn', onClickAction, this);
    panRightButton.onInputOver.add(onButtonOver, this);
    panRightButton.onInputOut.add(onButtonOut, this);
    panRightButton.onInputDown.add(panScreenRight, this);

    function panScreenRight() {
        game.camera.x += 10;
    }

我试过使用一个布尔标志( isPanning ),如果我点击一个按钮并且在发布时为假,则会变为true . 在 game.camera.x += 10; 上有一个while循环,但它只是减慢并停止了脚本 .

function onClickAction() {
     isPanning = true;
}

function onButtonOut() {
      isPanning = false;
}

function onButtonUp() {
      isPanning = false;
}

function panScreenLeft() {
    if (isPanning) {
         game.camera.x -= 10;
    }
}

1 回答

  • 3

    正确的方法是在 update 方法上,但不在循环中 . 使用标志来确定按钮是否被按下是正常的,但只需让Phaser更新摄像机位置,就像您已链接的示例一样:

    function update() {
    
        //...
    
        if (isPanningLeft) {
            game.camera.x -= 10;
        } else if (isPanningRight) {
            game.camera.x += 10;
        }
    
       //...
    }
    

    你不需要一个循环,因为 update 方法是在循环中执行的(并且它应该按帧执行一次)

相关问题