Lesson 42: Repeating the Background
1. Download the project files and view index.html in a web browser. Take a look at the image files that will be used in the game..
Open index.html in a browser. Use the arrow keys to move the player ship left and right.
Open index.html in an editor. Notice the HTML, CSS, and JavaScript are all in this file. You can separate these if you want. Notice there are only two elements in the body of the HTML, a div with an id of gameScreen and a div with an id of output.
In the CSS, notice the width and height of the gameScreen is not set. This is done in JavaScript. Also note that a style for all elements with the gameObject class is provided.
The JavaScript should be familiar, but there are some differences in how you have done things before. First, the GS_WIDTH and GS_HEIGHT constants are being used to set the width and height of the gameScreen. By setting these values in JavaScript instead of CSS, they will be easily accessible.
Also notice that adding elements (such as the ship img) to the gameScreen is done in JavaScript instead of CSS.
Be sure to go through all the code carefully so you have a clear understanding before you move on.
Illusion of movement
Often times you will want to move the background instead of the player character to give an illusion of movement. In this game, you want the player to feel as though they are always moving upward while the ship never actually moves up. You do this by having a background that continuously moves downward. You will use two backgrounds to ensure the background image always covers the gameScreen.
2. Add bg1 and bg2 as global variables and BG_SPEED as a global constant that will determine the speed at which the background moves.
3. In the init() function, create two img elements (saved to bg1 and bg2) for the background and add them to the gameScreen. Look in the project files folder and notice bg.jpg was created with the appropriate width of 800px, but a much larger height (1422px) than the gameScreen. These values are also set in the JavaScript. While bg1 is placed at the top, left corner of the gameScreen to be immediately visible, bg2 is placed just above the gameScreen.
At this point, the background should appear but not move.
4. Now just add the code into the gameloop() function to make the background continuously move.
That's it... the illusion of moving forward by continuosly moving the background is complete.