Step 3

Spawning the asteroids


Next add the following code, this will spawn a projectile that shoots down at a random x position.

Leave the image for the projectile blank for now, we’ll change that next.

Picking a random image from the list


Next, add the shown blocks of code to pick a random item from the asteroid array to use as the image.

Making sure the index is valid


Remember, when getting items from an array we always need to make sure we are using a valid index.

Add the following code to ensure that our index is valid. If this doesn’t make much sense to you, try checking out the previous project for a more in depth explanation.

Testing the code


Go ahead and test out your code. You should see lots of different asteroids flying through the game!