Previously we discussed the basics of Unity’s physics engine. Now we will take a quick look at collisions.
Collisions are the events that happen in Unity when two or more objects in the scene that are equipped with Colliders and Rigid Bodies come into contact or overlap in space.
Unity provides us with two main types of collision methods that assist us in scripting behaviors and interactions:
I will preface this by saying that there are a few more methods related to Collider events both for 3D and 2D physics and I will briefly mention them later. For now, I want to focus on these two.
The main difference you may notice beyond their name is the parameter that each method takes.
- OnCollisionEnter() takes a Collision type parameter that can give us information on Contact points or the velocity at which the collision took place. This is because the event gets detected at the point of contact between two or more colliders. For this method to work, the object that detects the event must have a Rigid Body attached to it.
- OnTriggerEnter() takes a Collider type parameter. This returns information on the Collider that was detected. The location at which this collision is detected is not necessarily the first contact point. Basically, OnTriggerEnter() is used to return information about GameObjects that enter the collider’s space.
In this example, the “enemy” sphere is being moved down with a script component that uses
transform.Translate() . When it comes into contact with the “player” cube the enemy’s movement is halted. Notice how there is some jitter in the enemy’s motion while it stops on the player. The script that is moving the sphere is trying to apply its calculations to the GameObject attempting to move it down but the player object is constantly blocking it. A collision is occurring!