Hello again. It's time to continue our infinite runner game.
Last time, we added the ability to move left and right to our avatar, as well as some basic obstacle spawning functionality. However, right now it spawns the same obstacle over and over, so we need to make it spawn different obstacles so the game is more challenging.
There are two ways to do this. The first way is to make a couple of changes to your spawn-obstacle state machine to make it randomize the X position of your obstacle within a specific range, as seen in the image below.
This will make the obstacles appear at any place within the width of the track.
Note that I set the range of the random float action between -2.4 and 2.4. The reason is that I took the time to test how far to the left or right I wanted it to be. Now, if you press play, you will see the obstacles appear at random points on the track.
Another way to do it is to have different pre-made configurations of obstacles and then pick them at random.
To pick a random obstacle every time, the easiest thing is to create an array that will contain all the obstacles and select a random one every time. You can make some modifications to your state machine as follows.
If you press play, you will see a different configuration is chosen every time, which adds different level of challenge to the game.
However, we still have another issue. The avatar can touch an obstacle and nothing really happens. If you are using a primitive as an obstacle, chances are your avatar stops in front of it due to the default collision, but that's it. We need the avatar to “die” when it touches an obstacle, so we have to create a routine that will do that.
First, go back to your obstacles, add a box collider and turn it into a collider (or turn the default collision into a trigger). Then, assign a new tag to your obstacle (something like “obstacle” could work). Then, add another cube as a child of your avatar, make it slightly bigger, and turn it into a trigger. What we will do is use this trigger to detect when your avatar hits an obstacle, and then trigger a game over. I opted for the simplest thing in this case: the trigger looks for its parent and then destroys the object, destroying the avatar as a whole. This causes the game to stop since there's no longer a player.
Of course, you can get more creative with your game over sequence. For example, you can simply make it “hide” the avatar (if your avatar object's body is not the root object, but rather a child of your player object), and then play a sound and spawn some particles. I am just giving you the basic steps so you can decide what to do next.
Right now, you should have an infinite runner with an avatar that runs down a track, as you evade different kinds of obstacles. Another thing we can do now is add some coins, so your game keeps track of a score, and also add some form of HUD so your score is visible on screen. We can take a look at that next time.