Adventures in Phaser with TypeScript–Handling Keyboard Input

 

 

In the previous part we looked at handling graphics in Phaser, now we are going to look at handling input.  This part is going to be code heavy and fairly light on description.  Look to the code comments for more details.

As is pretty common with game frameworks, there are a number of different ways to handle input and a number of different devices, so lets get started!

 

Using the cursor keys and polling for input

 

/// <reference path="phaser.d.ts"/>    // Demonstrate the use of arrow keys in a Phaser app  // This application demonstrates creation of a Cursor and polling for input  class SimpleGame {      game: Phaser.Game;      jetSprite: Phaser.Sprite;      cursors: Phaser.CursorKeys;        constructor() {          this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {              create: this.create, preload: this.preload,          update: this.update});      }        preload() {          var loader = this.game.load.image("jet", "jet.png");      }        create() {          var image = <Phaser.Image>this.game.cache.getImage("jet");          this.jetSprite = this.game.add.sprite(              this.game.width / 2 - image.width / 2,              this.game.height / 2 - image.height / 2,              "jet");            // create the cursor key object          this.cursors = this.game.input.keyboard.createCursorKeys();      }        update() {          // Update input state          this.game.input.update();            // Check each of the arrow keys and move accordingly          // If the Ctrl Key + Left or Right arrow are pressed, move at a greater rate          if (this.cursors.down.isDown)              this.jetSprite.position.y++;          if (this.cursors.up.isDown)              this.jetSprite.position.y--;          if (this.cursors.left.isDown) {              if (this.cursors.left.ctrlKey)                  this.jetSprite.position.x -= 5;              else                  this.jetSprite.position.x--;          }          if (this.cursors.right.isDown) {              if (this.cursors.right.ctrlKey)                  this.jetSprite.position.x += 5;              else                  this.jetSprite.position.x++;          }      }  }    window.onload = () => {      var game = new SimpleGame();  };  

 

When you run this code the familiar jet sprite is rendered centered to the canvas. You can then use the arrow keys to move the fighter around.  As you can see, in the state for each key is information on modifier keys like Control and Alt.  Polling for input ( that is, checking status each call to update ) is a valid way of controlling a game, but sometimes you instead want to respond to input as it arrives.  Let’s look now at an example of event driven keyboard handling:

 

/// <reference path="phaser.d.ts"/>    // Demonstrate keyboard input handling via callback  class SimpleGame {      game: Phaser.Game;      jetSprite: Phaser.Sprite;      W: Phaser.Key;      A: Phaser.Key;      S: Phaser.Key;      D: Phaser.Key;        constructor() {          this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {              create: this.create, preload: this.preload          });      }        preload() {          var loader = this.game.load.image("jet", "jet.png");      }        moveLeft() {          this.jetSprite.position.add(-1, 0);      }      moveRight() {          this.jetSprite.position.add(1, 0);      }      moveUp(e: KeyboardEvent) {          // As you can see the event handler is passed an optional event KeyboardEvent          // This contains additional information about the key, including the Control          // key status.          // Basically if the control key is held, we move up or down by 5 instead of 1          if (e.ctrlKey)               this.jetSprite.position.add(0, -5);          else              this.jetSprite.position.add(0, -1);      }      moveDown(e: KeyboardEvent) {          if (e.ctrlKey)              this.jetSprite.position.add(0, 1);          else              this.jetSprite.position.add(0, 1);      }        create() {          var image = <Phaser.Image>this.game.cache.getImage("jet");          this.jetSprite = this.game.add.sprite(              this.game.width / 2 - image.width / 2,              this.game.height / 2 - image.height / 2,              "jet");            // Create a key for each WASD key          this.W = this.game.input.keyboard.addKey(Phaser.Keyboard.W);          this.A = this.game.input.keyboard.addKey(Phaser.Keyboard.A);          this.S = this.game.input.keyboard.addKey(Phaser.Keyboard.S);          this.D = this.game.input.keyboard.addKey(Phaser.Keyboard.D);            // Since we are allowing the combination of CTRL+W, which is a shortcut for close window          // we need to trap all handling of the W key and make sure it doesnt get handled by           // the browser.            // Unfortunately you can no longer capture the CTRL+W key combination in Google Chrome          // except in "Application Mode" because apparently Google thought an unstoppable un prompted          // key combo of death was a good idea...          this.game.input.keyboard.addKeyCapture(Phaser.Keyboard.W);            // Wire up an event handler for each K.  The handler is a Phaser.Signal attached to the Key Object          this.W.onDown.add(SimpleGame.prototype.moveUp, this);          this.A.onDown.add(SimpleGame.prototype.moveLeft, this);          this.S.onDown.add(SimpleGame.prototype.moveDown, this);          this.D.onDown.add(SimpleGame.prototype.moveRight, this);      }  }    window.onload = () => {      var game = new SimpleGame();  };  

 

As you can see, you can also create Phaser.Key objects and attach onDown event handlers ( technically Signals ) to each.  Of course you can reuse the same handler for multiple keys.  A couple key things to notice here… unlike the previous example, holding down a key will not cause continuous movement.  You must press and release the key over and over.  If you want constant movement, either use a polling method, use and action instead of updating each frame, or add some logic to move until the key is released.

 

The other thing to be aware of here is the use of the CTRL+W combination and addKeyCapture().  addKeyCapture() allows you to prevent the event from bubbling up, so once you’ve handled the key combination, it’s done.  Otherwise it would keep being passed up, either to other objects in the scene, or to the browser itself.  You can also use addKeyCapture to prevent default web behavior, such as scrolling when SPACE is pressed.

 

Programming


Scroll to Top