Handling keyboard input

In this section, we are going to provide keyboard support for our minigame. Our users should be able to use the cursor keys to move the ship in all directions. To access the state of the keyboard keys, we need a global variable to hold the state of the pressed keys. Let's learn how to do this:

  1. Let's call it cursors and put it under the game instance:
      const game = new Phaser.Game(config);
let cursors;
  1. The create function allows you to access the input.keyboard object. You can use this object to retrieve a reference to the cursor keys' state:
      // Create cursors
cursors = this.input.keyboard.createCursorKeys();

According to the official documentation, this creates a new object called cursors. It contains four objects: up, down, left, and right. These are all Phaser.Key objects, so anything you can do with a Key object you can do with these.

  1. Now, we can check the state of the keys in the update method. As you may recall, the update method usually gets called multiple times per second, so it is a perfect place to check the state of the input controls and update the game accordingly:
      function update() {
if (cursors.right.isDown) {
ship.x += 2;
}
}
  1. Every time the update method is invoked, we check the state of the right key and increment the horizontal position of the ship by 2 if the key is in the pressed, or down, state. In the same way, if the left key is pressed, we decrease the horizontal position of the ship by 2, as shown in the following code:
      function update() {
if (cursors.right.isDown) {
ship.x += 2;
} else if (cursors.left.isDown) {
ship.x -= 2;
}
}
  1. Now, we can navigate our spaceship horizontally, and it shouldn't difficult for you to support the vertical axes as well. Please refer to the following code snippet to get an idea of how to perform vertical navigation:
      function update() {
if (cursors.right.isDown) {
ship.x += 2;
} else if (cursors.left.isDown) {
ship.x -= 2;
} else if (cursors.up.isDown) {
ship.y -= 2;
} else if (cursors.down.isDown) {
ship.y += 2;
}
}
  1. Now, restart your Electron game and try using the keyboard keys. Notice how the ship moves in all four directions:

In this section, you have successfully implemented keyboard support for your game project. We received the cursor key's state and changed the coordinates of the ship according to user actions. Now, let's make the ship's behavior more natural and make it face the direction it's moving in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset