Objective: Understanding the basics of how Colliders and Triggers work.
Continuing to build this Galaxy Shooter game, I am now up to a point where I require my game objects to be colliding and interacting with each other and need to decide which method between OnCollisionEnter and OnTriggerEnter is going to function best. I need my Laser that is shot from the Player to interact with the Enemy and I also need the Enemy to interact with the Player if they collide, but I am not interested in having my game objects simulate the effects of physics on their Rigidbodies as I am planning to create an explosion effect and have the game object disappear. Let’s start by looking into a Collider and a Trigger:
Collider Vs Trigger
Colliders are Components that are built into Unity which provide collision detection through the various green lines (or boundaries). They define the shape of game objects for the purposes of physical collision. There must also be one Rigidbody attached to one of the game objects. In the example below we can see a simple 3D cube with the green border lines around it, this is a simple Box Collider. This can be manipulated to be larger or smaller than the box depending on the objective for your game and how you want Unity’s Colliders to interact with each other utilising Unity’s physics system. Multiple Colliders can be added to a single game object and Unity also provides simple primitive Colliders such as Box, Sphere, Circle and Capsule.
Let’s turn our Gravity off on the Rigidbody as I won’t be using this in my game:
The 2 game objects are going to Destroy once they collide:
Now I have removed the Destroy method and they should just keep colliding with each other as if running into a wall:
Triggers are a special setup of the Colliders that give them the ability to trigger events when they touch each other or overlap. The 2 objects won’t collide anymore (they will simply pass through each other) if one of the Colliders is setup as a Trigger as it will use the event system. It is at this stage, when the Trigger event occurs, that you can decide how you wish to set this up depending on the objective of your game. You must also have a Rigidbody attached to one of the game objects.
E.g. We can manipulate the Collider around the game object so that we can Trigger an event to occur much sooner. I have made the Box Collider much larger on the cube and you will now see that when the 2 Colliders touch each other a Collision will no longer occur because it is setup for “Is Trigger” (I have also removed the Destroy game objects code).
Now, let’s add some code so that the Enemy gets destroyed about half way down the map when it triggers with the Enlarged Box Collider. We are now going to use the method OnTriggerEnter() instead of OnCollisionEnter():