Implementing menu keyboard controls

Hello forum. I want to be able to navigate menu with both mouse and arrow keys. Are there any good examples how to do it?

I need:

  • Set last hovered control item as focused
  • Loop through control items with ‘ArrowDown’, ‘ArrowUp’
  • Make code reusable

import config from ‘config’;
import CST from ‘consts’;
import buttons from ‘consts/buttons’;

import { version } from ‘…/…/package.json’;

const { btnDefault, btnFocused } = buttons.textButtons;

export default class TitleScene extends Phaser.Scene {
constructor() {
super(CST.SCENES.TITLE);
}

create() {
this.add
.text(config.width - 25, 25, ‘[PLAY]’, btnDefault)
.setOrigin(1, 0)
.setInteractive({ useHandCursor: true });

this.add
  .text(config.width - 25, 60, '[OPTIONS]', btnDefault)
  .setOrigin(1, 0)
  .setInteractive({ useHandCursor: true })
  .on('pointerdown', () => this.scene.start(CST.SCENES.OPTIONS));

this.add
  .text(config.width - 25, 95, '[CREDITS]', btnDefault)
  .setOrigin(1, 0)
  .setInteractive({ useHandCursor: true })
  .on('pointerdown', () => this.scene.start(CST.SCENES.CREDITS));

this.add
  .text(config.width - 25, config.height - 25, '[EXIT]', btnDefault)
  .setOrigin(1, 1)
  .setInteractive({ useHandCursor: true });

this.input.on('pointerover', (e, gameObjects) => {
  gameObjects[0].setStyle(btnFocused);
});

this.input.on('pointerout', (e, gameObjects) => {
  gameObjects[0].setStyle(btnDefault);
});

this.add.text(25, config.height - 25, version).setOrigin(0, 1);

}
}

Also, are there any pre-made solutions for ui components?

Found an example: https://sbteam.itch.io/surge-breaker
No source code though :disappointed_relieved:

It’s probably not the easiest way how I did it, but I wanted to play around with the Phaser events a bit. Hope it helps tought :slight_smile:

I will check it out, thanks!