HTML and CSS Reference
In-Depth Information
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 iniial 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 funcion to set the lane posiion 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
funcion 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;
player.element.classList.remove('lane1');
player.element.classList.remove('lane2');
player.element.classList.add('lane'+player.currentLane);
};
4. When the player clicks on the let or right buton, we move the player let or
right correspondingly. Therefore, we define the following moveToLeftLand
and moveToRightLane methods to map with the left and right keys:
player.moveToLeftLane = function() {
player.changeLane(1); // special case for 2 lanes.
};
player.moveToRightLane = function() {
player.changeLane(2); // special case for 2 lanes.
};
 
Search WWH ::




Custom Search