OnCollisionEnter Vs OnTriggerEnter in Unity
Objective: To follow on from the previous article for Colliders and Triggers to help determine which method will work best for our game.
Following on from the previous article that describes Colliders and Triggers, let’s run through some information on OnCollisionEnter(Collision collision) and OnTriggerEnter(Collider other).
This method is called when the Collider/Rigidbody of one game object has touched the Collider/Rigidbody of another object. It also requires a Rigidbody to be present on the one of the game objects. In comparison to OnTriggerEnter(), it is passed the Collision class (instead of Collider) which contains information about the collision itself. E.g. Relative velocity, contact points, contact count, impulse, Rigidbody and Game object etc.
This method is called when a game object collides with another game object (when both of the colliders touch) whilst one of the game objects has ‘Is Trigger’ ticked on their Collider. Both of these objects must contain a Collider component. If both of the game objects have this same box ticked, a collision won’t occur. One of the game objects must also contain a Rigidbody.
E.g. In the Enemy script let’s add the following code:
Here we are utilising Unity’s ‘Tag’ feature when our game objects collide to access the other game objects information. If you are unsure how to create and add a tag simply look in the top of the Inspector panel for this:
Click on the drop down box and press ‘add tag’. Click the + symbol under the tags heading to create a new tag. Input your new tag name and hit Save. Then click on the game object you want to update and press the drop down box next to Tag and click the required tag.
Let’s also make sure that one of our colliding game objects has the ‘Is Trigger’ ticked, in this case I have chosen the Enemy as it is colliding with both the Laser and the Player.
Don’t forget to also have the Rigidbody attached to one of the game objects. Again, I have chosen the Enemy as it is going to be colliding with both other game objects. As I don’t want the Enemies Rigidbody to be affected by physics, I am going to change the Body type from Dynamic to Kinematic.
The above code was only searching for the Laser, so now let’s add the Player also:
As you can see the If and Else If statements methods are the same apart from the tags of ‘Laser’ and ‘Player’. As these are the same we can tidy this up a little bit using the || (or) symbol whilst detecting the other.tag as shown below:
As I will be implementing a lives system for the Player this code will need to be revised as the Player is going to remain alive and not be destroyed when hit but it is always nice to learn some new logic!