Adventures in GameDev with GameDevHQ! Day 14: OnCollisionEnter & OnTriggerEnter and when to use them.
We discussed Collisions and Triggers yesterday as they are both methods of the Collider Class. Whenever you put a Box collider, Capsule Collider, SphereCollider or any type of collider on your object, you’re going to have this classes options available to you and using them, you can specify whether you want to check for hard collisions or trigger collisions using the ‘isTrigger’ checkbox.
So what’s the difference? OnCollision contains physics information for your object. Mass, velocity, friction, etc. and it helps unity in calculating the motion of the objects when they combine with one another. If we made a racing game, we’de be placing colliders on each car and if they hit each other, unity would figure out the physics of how each car would react during the crash and then animate them automatically appropriately.
Whereas OnTriggerEnter(Collider other) does NOT have a solid body or any physics information and only looks for a collision. Think of Sonic when he collects rings, When sonic hits a ring, each has a box collider, but the ring would be a trigger collider meaning Sonic would continue to race through and collect the ring without slowing down because there’s no physics pushing back on him!
Simply put, if you need something to ‘crash’, use a OnCollisionEnter, but if you’re ‘collecting’ or don’t need an object to physically affect the other and you just want to know whether the object has passed through it, that’s when you use OnTriggerEnter.
That’s it for today! Tomorrow we’ll discuss Script communication in Unity using GetComponent.