Lesson 44: Adding Properties to Objects
Elements have built-in properties. For instance, a div has a width, height, visibility, left, top and many more. Similarly, an img has those properties plus others, such as the src property.
You can add additional custom properties to elements. For instance, if you have many img elements that you want to move around at different speeds, you could give the element a custom property of speed. In fact, that is what you will be doing in this lesson with all of the enemy ships.
1. Create an enemies Array to store each of the enemy ships.
2. In the init() function, add a for loop to generate 10 enemy ships (img elements), adding each ship to both the gameScreen the enemies Array.
Notice that instead of setting the left and top here, a custom placeEnemyShip() function is used. This is because you will not only be placing the ship when the page loads, but also each time the ship has flown through the screen.
3. Create the placeEnemyShip function so that it randomly generates a new location above the gameScreen and a new speed between 6 and 15.
Note the variable name e was used to represent the (e)lement, or the (e)nemy, that was sent to the function.
Of course, you should also see that the custom speed property was created and assigned a value quite simply.
Lastly, notice that the GS_WIDTH constant and the element's width is used to determine the maximum left (X) value that the ship could have.
4. Now that the ships have been created and added to the gameScreen and the enemiesArray, add the code in gameloop() to move those ships down the gameScreen repeatedly.
This code loops through each element of the enemies Array to change their positions. When one of the enemy ships moves all the way through the gameScreen, the ship is set to a random new position and speed using the placeEnemyShip() function. Otherwise the ship is set to a new position by increasing the top value by the ship's speed.
Now the 10 enemy ships will repeatedly move downward through the gameScreen at different speeds.