Player’s collision with other objects

Once two objects collide with each other, there are two paths you can take. The first is to ignore the collision. This is useful when the player might have collided with a wall and all you want to do is just to stop the player from moving past the wall.

On the other hand, if you do want logic executed when two objects collide with each other, Unity provides two ways: OnCollisionEnter() and OnTriggerEnter().

Both requires the objects to have colliders on them. This could be as simple as a Box collider to something as complex as a Mesh collider. Futhermore, if you want to calculate realtime collision physics between the objects, both objects must have a rigidbody attached to them. If not, Unity will detect those without a rigidbody as static and will not calculate collision between the objects.

The main differences between OnCollisionEnter and OnTriggerEnter is essentially how you want the objects to act between the colliding objects. For instance, if you just want one object to “bounce” off the other but want to execute logic, you’re better off choosing OnCollisionEnter. For example, whenever the player jumps on an enemy, the player doesn’t faze through the enemy but you still want to destroy the enemy. As a result, destroying the enemy in the OnCollisionEnter method is the best way.

Nevertheless, what if you do want one object to go through the other? First, you’ll need to set at least one collider or rigidbody to IsTrigger. By doing this, one object can pass through the other and you can incorporate the OnTriggerEnter into one of the scripts in order to execute logic. As an example, whenever the player collect power-ups, you want the player to go through them and not have them bounce off. Therefore, by executing the OnTiggerEnter and enabling IsTrigger on the power up, the player can pass through and get the benefits of the power up.