Creators – Week 8

This week we finished off our feeding animals game and played another challenge round. This concludes our second project and we’ll be starting on a brand new project after Christmas.

Collisions in Unity

There are two types of collider objects in Unity:

  1. A collider that acts like a solid barrier (standard collider)
  2. A collider that allows things to pass through it, but detects the collision (a trigger collider)

There is an “Is Trigger” check box on all collider components that allows us to change the type.

Standard colliders are used for physical interactions – like walls you can’t pass. Trigger colliders are used detect things being in the same space, but not physically interacting.

To detect collisions between two objects in Unity:

  1. Both of them have to have collider components attached
  2. At least one of them needs a RigidBody component attached

When Unity detects collisions, it sends messages to all components on the impacted GameObjects. We can choose to receive these messages by having the right functions in one (or more) of our components:

  1. For physical collisions we implement OnCollsionEnter()
  2. For trigger collisions we implement OnTriggerEnter()

These are similar but differ in information they receive.

Adding Collision to Our Prefabs

We selected each of the prefabs in our Prefabs folder and added a Box Collider to them. In the Game View we used the “Edit Bounding Volume” tool, as shown below, to adjust the Box Collider to make it a good fit.

To the Pizza Slice Prefab, we added a Rigid Body component and make sure to clear the option to “Use Gravity”.

We created a new script called DetectCollisions.cs and attached it to the animal prefabs. Editing this script we added the following function:

void OnTriggerEnter(Collider other)
{
  Destroy(gameObject);
}

Testing our code after this, we note that the animals disappear when they’re hit by a piece of pizza, but the pizza slices keep going. Once more change allows this code to remove the pizza slice as well:

void OnTriggerEnter(Collider other)
{
  Destroy(gameObject);
  Destroy(other.gameObject);
}

A Very Basic “Game Over”

We implement the most basic possible “Game Over’ message by updating the Update() function in DestroyOutOfBounds.cs as follows:

    void Update()
    {
        if (transform.position.z > topBound)
        {
            Destroy(gameObject);
        }
        else if (transform.position.z < lowerBound)
        {
            Destroy(gameObject);
            Debug.Log("Game Over!");
        }
    }

Now, when an animal reaches the bottom of the screen, the message “Game Over” gets printed to the Console window Unity.

Code Download

The code for this week’s project is on our GitHub, as always.