Step 3

Creating an enemy


Next let’s create a function called “createEnemy” and add the shown code inside it.

Notice the position we chose. It will always be on the very right of the screen. However, for the y position, we want it to pick one of our three lanes at random. This is a bit more code and can look a little confusing at first, but it’s not that bad once you understand it.

Picking a random lane


Next add the code that is shown. This allows us to pick a random value from our array, giving our enemy a random y position to spawn at, but wait we’re not done yet!

Picking a valid index


Remember, we just can’t pick any random number when using an array. We need to make sure any number we pick is a valid index within the array.

Because of this, the random number we pick must be between 0 and (length of array – 1).

Spawning the enemy


Lastly, add the following code. An enemy should now randomly spawn in each of our three lanes!