The purpose
When creating games with Phaser 3, pressing the up and down arrow keys can sometimes unintentionally cause page scrolling.
(This is less noticeable when scaling to fit the local environment, but it often becomes apparent after uploading to a server, possibly due to the influence of ads.)
This prevents unintended scrolling.
Implementation
This code will be added to scenes requiring the user to press the up and down space keys.
Calling this in create()
will work 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();
});
Because multiple processes can be added with on()
, there’s no need to merge processes; you can call the above code even if other processes are registered with on()
for the top and bottom spaces.
While there is a similar keyup-XXXX
event, page scrolling is handled by the keydown-XXXX
event.
Result
We are able to prevent the page from scrolling when the up and down space keys were pressed in Phaser3. (This is a bit awkward due to “space keys” being redundant. See option 2 for improvement)
comment