This content originally appeared on Level Up Coding - Medium and was authored by Dennisse Pagán Dávila
OnCollisionEnter vs. OnTriggerEnter — When to use them
Colliders are added to GameObjects to reflect their physical structure and to simulate real-world physics.
By default, an object with a Rigidbody Component will always collide with an object that has a Collider Component.
Colliders may be used as Triggers as well as blocking Rigidbodies. When a Collider is set as a Trigger, it can detect interactions with other game objects.
Even though Colliders are used as a physical representation of our objects, that does not mean you have to shape them to match the exact silhouette of the object. Your player character may have a complex shape, but you can apply a Box Collider or even a Capsule Collider.
How can I tell which one to use?
An easy way to differentiate between the two is to think of them visually. OnCollisionEnter can be visualized as colliding against a wall, and OnTriggerEnter can be visualized as triggering an alarm.
Let’s take a look at them individually.
OnCollisionEnter
This is mainly used for solid interactions. In this code sample, the parameter variable “other” refers to the other game objects that can be registered as collisions. For instance, it can be used to make the player character solid and not some entity that can pass through other objects, or even fall through the floor.
No Collider
With Collider
It can also be used for objects that collide against the environment and other game objects.
Example: A car that actually crashes against other game objects like walls.
OnTriggerEnter
Rigidbodies are unaffected by triggers, and as such, a game object with a Rigidbody will be able to move through it and trigger a reaction through code. Use a Trigger to activate alarms, collectible powerups, and even build environmental hazards like traps that spring to life once you step on a specific area.
Example: The line at the end of a race is a Trigger — you are not colliding with it, but once you interact with it, the game knows you’ve won the race.
In the next article, I will be discussing how scripts communicate in Unity.
OnCollisionEnter vs. OnTriggerEnter — When to use them was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Dennisse Pagán Dávila
Dennisse Pagán Dávila | Sciencx (2021-04-06T15:15:37+00:00) OnCollisionEnter vs. OnTriggerEnter — When to use them. Retrieved from https://www.scien.cx/2021/04/06/oncollisionenter-vs-ontriggerenter%e2%80%8a-%e2%80%8awhen-to-use-them/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.