Creating obstacles

Of course, the game wouldn't be fun without any challenges so we're going to add in the pipe-like obstacles that the player will also need to avoid.

  1. From the Art Assets folder, bring in the rockGrass and rockGrassDown sprite and place it into the Assets/Sprites folder from the Project tab.
  2. Drag and drop the rockGrass object into the world. Change its position to 0, -2.5, 0. Then, add a Polygon Collider 2D component to it.
  3. Afterwards, drag and drop the rockGrassDown object into the world. Change its position to 0, 2.5, 0. Then, add a Polygon Collider 2D component to it.
  4. Next, create an empty game object by selecting GameObject | Create Empty. Reset its position to 0,0,0 and then rename it to Obstacle. Afterwards, drag and drop the two rockGrass objects to it to become the Obstacle object's children:
    Creating obstacles
  5. Now, we want the obstacle to move like the RepeatingBehaviour script does, except instead of repeating, we want to remove it so we can respawn. Create a new C# Script named ObstacleBehaviour and use the following code for it:
    using UnityEngine;
    
    public class ObstacleBehaviour : RepeatingBackground {
    
        protected override void Offscreen(ref Vector3 pos)
        {
            Destroy(this.gameObject);
        }
    }

While it may not look like a lot, quite a lot is going on here. Note that instead of MonoBehaviour to the right of the :, we now have RepeatingBehaviour. What this does effectively is have ObstacleBehaviour inherit everything that the RepeatingBehaviour class has. This means that all of the properties and functionality are included from the previous script. This will allow us to only write code to extend or override the behavior from the original. In this case, we want to destroy the obstacle when it goes off screen, so all we do is override the Offscreen function (which we can only do if we made the function virtual earlier) to now destroy the game object this was attached to before.

Note

For more information on inheritance and derived classes, check out https://msdn.microsoft.com/en-us/library/ms228387(v=vs.90).aspx.

Save the script, then attach the newly created script to the Obstacle object, and set the Scroll Speed property to 5.

At this point, the obstacle will now go off screen, and afterwards, it'll destroy itself automatically!

..................Content has been hidden....................

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