Friday, August 21, 2015

Using Touch with Phaser

My goal for Amphibian.com was to develop it as a mobile-first webcomic. That's why it reads vertically and uses SVGs for graphics that stretch and shrink to any size. A year's worth of client browser stats, however, informs me that mobile users are still in the minority on the site. Nonetheless, I still want to make sure everything on there works on phones and tablets.

That includes my 404-page frog soccer game.

Up until now, I've been developing it as a way to learn how to use Phaser for game development and have been focused on the basics. It was more common to take input from the keyboard in the examples so that's all I've been doing. But today I found it was very easy to add touch controls - at least in my game.

There are two places where the keyboard is used in my game.
  1. Hit the space bar to start playing
  2. The arrow keys move the frog
Starting the game with either the spacebar or a tap (or mouse click) was simple:

function update() {

    // ... other update stuff ...

    if (mode === WAIT_MODE && (spacebar.isDown || game.input.activePointer.isDown)) {
        mode = PLAY_MODE;
    }

    // ... other update stuff ...

}

In Phaser, game.input.activePointer normalizes input from the touchscreen and the mouse, and its isDown property is an easy way to check if any button has been clicked or the screen has been touched in any way. If you wanted to get more specific with mouse input, there are other properties that represent the individual buttons. With touch input, you have the option of reading location data from multiple pointers as a way of supporting multitouch, but none of that was necessary for my game. I just want to know that you've touched or clicked to start the play.

The other type of input, from the arrow keys, seemed like it might be more difficult to reproduce with touch input. Not at all! I was impressed with how simple it was to direct the frog based on touching the screen.

function update() {

    // ... other update stuff ...

    if (mode === PLAY_MODE) {

        if (game.input.activePointer.isDown) {
            game.physics.arcade.moveToPointer(frog, 180);
        }

    }

    // ... other update stuff ...

}

Basically, the code above just checks to see if the user is touching the screen or holding down a mouse button. If they are, the frog is directed towards wherever the pointer is located. For mouse input, that's the cursor location. For touch input, it's the location of your finger. Couldn't be easier!

With just these few lines of code I was able to touch-enable my game. I'm still struggling with the canvas size and page navigation on mobile, but it is playable. Give it a try: http://amphibian.com/404/. Don't forget that you can see the complete source code on GitHub!

After playing a few rounds, make sure you read today's comic as well.

No comments:

Post a Comment