OnCollisionEnter Vs. OnTriggerEnter

When to use them?

Day 7 — Aspiring Game Creator

2D Game Dev: Galaxy Shooter

Unity’s Physics Engine offers various methods when dealing with collisions. Collisions are either physical or just event triggers.

First, in order for game objects to make use of the physics engine, they must have the correct components: collider & rigidbody. Regardless of 2D or 3D, collision or trigger, all game objects need colliders. So far as the rigidbody goes, usually the ‘main’ game object or at least the game object doing all the colliding should have the rigidbody component.

OnCollision methods will return collision information, contact points and impact velocity, whereas OnTrigger methods return only the opposing collider.

The three methods are: OnEnter, OnStay and OnExit. Enter is called only once when two colliders initially touch. Exit is called only once when the collision between the two colliers ends. Stay is called as long as the collision is still in effect.

Pseudo Logic:

At this stage in Galaxy Shooter the player spaceship can collide with enemies and enemies can collide with lasers. Makes sense to at least start adding the rigidbody to the Enemy Prefab.

Next time a game object is added to the game, let’s say, an asteroid, the lasers will not be able to interact with it unless the rigidbody is added to the asteroid or the laser. Rethink the logic: lasers collide with everything and all other game objects could collide with the player, so maybe the player and laser should have the rigidbody component. But will the asteroids and enemies ever exist in the same scene?

Best Practice: Even in a small game like Galaxy Shooter a matrix of rigidbodies and colliders should be maintained.

When to use OnCollision vs OnTrigger?

OnCollisionEnter: If the game requires two or more game objects physically affecting one another then a hard collision is what is needed and using the OnCollisionEnter method is required to discover information about the collision.

Hard collisions in Galaxy Shooter not so good!

OnTriggerEnter: If the game only requires an event trigger — a pass through collision — then the OnTriggerEvent is the method required.

Triggered collisions, events handled by code … Better!

Aspiring Game Creator