Extending the level

At the moment, Jake moves forward and eventually will run to the edge and drop. To avoid this, we will simply generate the next piece of the level every time the player leaves one level piece behind. We will also destroy the old and already used piece of level to keep things clean.

We will use the OnTriggerEnter method to recognize when the player reaches the ExitTrigger of a certain level piece:

Extending the level

First things first; we need to make sure that our level generator contains the functionality needed to extend the level. Let's add the Remove OldestPiece void method to the level generator.

With your coding experience, you should easily understand line by line what we are doing in this method. If you don't, just remember that this method will remove the oldest levelPiece from the level.

We are getting closer to a working endless level. The last piece of the puzzle that is missing is calling the AddPiece and RemoveOldestPiece methods when the Player game object enters the trigger.

Let's write one more component that we will add to the LeaveTrigger game object in every LevelPiecePrefab. Create a new C# script and call it LeaveTrigger.

Extending the level

The OnTriggerEnter2D method is called automatically by Unity whenever RigidBody2D enters the 2D collider. If you look closely at the Player game object, you will see that one of its components is a Rigidbody. Where is our trigger then? We actually have a game object called LeaveTrigger as a child of LevelPieceBasic. In theory, we have all the parts needed for the OnTriggerEnter2D method to be called on the LeaveTrigger.

Add the LeaveTrigger component to the LeaveTrigger game object and click on Play in Unity.

What should happen? After you press S to start the game, Jake will run through the level. As soon as he enters the LeaveTrigger game object, we will call the AddPiece method to extend the level and the RemoveOldestPiece method to clean up the oldest piece in the level.

Please note that you can observe level generation only in the scene view. Why? Because the Main Camera we are using to render what is happening is in a static position right now. We will add a smart script to the camera very soon to make it follow the Player game object:

  1. Download CameraFollow.unitypackage from the Packt hub and import it to your project.
  2. Add the CameraFollow component to the Main Camera game object.
  3. Drag the Player game object into the Target slot in the Camera Follow component, as shown in this image:
    Extending the level
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset