Prevent page scrolling when the up or down spacebar is pressed (Phaser3)

この記事は約3分で読めます。
スポンサーリンク

Things I want to do

When creating a game with Phaser3, pressing the up or down spacebar may unintentionally scroll the page.

(This can be difficult to notice if you’ve configured it to scale to fit your local environment, but it can become apparent when you upload it to the server due to the influence of advertisements, etc.)

This will stop the intended scrolling.

スポンサーリンク

implementation

Add the following code to the scene where you need to press the up or down spacebar.

Calling it with create() is fine.

this.input.keyboard.on('keydown-DOWN', event => {
        event.preventDefault();
});
this.input.keyboard.on('keydown-UP', event => {
        event.preventDefault();
});
this.input.keyboard.on('keydown-SPACE', event => {
        event.preventDefault();
});

Furthermore, since multiple processes can be added using on(), even if you have registered other processes using on() for the spaces above and below, there is no need to merge the processes; calling the above code will work without any problems.

There is a similar event called keyup-XXXX, but page scrolling is handled by the keydown-XXXX event.

スポンサーリンク

Result

I was able to prevent the page from scrolling when pressing the up or down spacebar in Phaser3.

コメント

タイトルとURLをコピーしました