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:
- 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; }
- 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); }
- 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 thelane1
andlane2
classes:player.changeLane = function(lane) { player.currentLane = lane; player.element.classList.remove...