Lesson 47: Creating Platforms
Tired of learning new JavaScript commands? Need some practice with all that you have already learned? Here is your chance. In this set of lessons, you will use only JavaScript commands introduced in previous lessons to create a side-scroller platform game.
1. Familiarize yourself with the code in the Project Files.
The HTML includes a pc (player character) div inside of a gameWindow div. An output div is included for debugging purposes. And the init() function is called when the page loads.
These elements are styled in the CSS so that the red pc is positioned relative to the black gameWindow. Note there is also a link to the myGameLibrary.js file that has the hittest function you used in previous lessons.
The JavaScript includes the declaration of global variables (and one constant). The init function sets the initial size and location of the pc and starts the game loop.
The gameloop function repeats every 50 milliseconds. That is 20 times per second. Currently, the gameloop is only used to move the pc when the left or right arrow key is pressed down. The keyboard event listeners along with leftArrowDown and rightArrowDown variables are used to detect when the arrow keys are being pressed.
All of this sets up a simple gamescreen with a red PC that can be moved back and forth across a black background using the left and right arrow keys.
2. Write code to enable you to quickly create platforms.
Start by creating a class that will be used to style all platforms.
In the JavaScript, add platforms as a global variable.
In the init function, set platforms to an Array and add a function call to addPlatform. This function will create and add a new platform given the location (x and y position) and the size (the width and height).
Create the addPlatform function. The function should create a div for the platform, style it with the platform class, position and size it with the parameters that were passed to the function, and then add it to the platforms Array and to the gameWindow.
Now a platform should appear in the gameWindow.
3. Add in gravity and collision detection.
Recall the constant GRAVITY and the variable fallSpeed that were declared globally with initial values of 1 and 0, respectively. In the gameloop function, add the code to increase fallSpeed and move the pc down by that amount.
Then loop through the Array div elements (platforms) to check if any of them collided with the pc. When a collision occurs, the fallSpeed should be set to 0 and the pc should be moved to the top of the platform so that it does not remain in front of it.
Now the pc will land on the platform, and stay on the platform until the player moves too far to the right or left, at which point it falls further.
Because the code was created with the intent of adding platforms quickly, only one line of code is needed to add another platform.
Each new platform that is added will already have collision detection!