Book Image

HTML5 Game Development Hotshot

By : Seng Hin Mak, Makzan Makzan (Mak Seng Hin)
Book Image

HTML5 Game Development Hotshot

By: Seng Hin Mak, Makzan Makzan (Mak Seng Hin)

Overview of this book

Table of Contents (15 chapters)
HTML5 Game Development HOTSHOT
About the Author
About the Reviewers

Controlling a player with the keyboard

In this task, we will allow the player to control the character to switch between the left and right lanes.

Engage thrusters

The following steps add the keyboard input logic to control the running avatar:

  1. We will set the visual and initial placement of the player by using CSS styles. Append the following styles to the game.css file:

    #player {
      position: absolute;
      width: 100px;
      height: 100px;
      background-image: url(../images/running.png);
      bottom: 100px;
  2. Now, we use the translate function to set the lane position of the player:

    #player.lane1 {-webkit-transform: translate3d(100px, 0, 0); }
    #player.lane2 {-webkit-transform: translate3d(200px, 0, 0); }
  3. Let's move to the logic part. In the player.js file, we append the following function that handles lane changing. To change the lane, we toggle the player element between the lane1 and lane2 classes:

    player.changeLane = function(lane) {
      player.currentLane = lane;