Last Updated on 2021-10-29 by Clay
In the process of making games with Unity, we usually need to deal with some collisions of game objects. For example: Get items, Hit the wall... and so on in different situations. At this time, we can OnCollisionEnter()
and OnTriggerEnter()
to handle collisions and trigger events.
The following record how to write collisions and trigger program, and the different Body Type situations.
Collision and Trigger
I am developing 2D game, so take the 2D game as an example.
Collision:
private void OnCollisionEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Snake")
{
Destroy(gameObject);
}
}
Trigger:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Snake")
{
Destroy(gameObject);
}
}
Demo:
Different Physical Collision Trigger Table
collision detection occurs and messages are sent upon collision
Static Collider | Rigidbody Collider | Kinematic Rigidbody Collider | Static Trigger Collider | Rigidbody Trigger Collider | Kinematic Rigidbody Trigger Collider | |
Static Collider | Y | |||||
Rigidbody Collider | Y | Y | Y | |||
Kinematic Rigidbody Collider | Y | |||||
Static Trigger Collider | ||||||
Rigidbody Trigger Collider | ||||||
Kinematic Rigidbody Trigger Collider |
Trigger message are sent upon collision
Static Collider | Rigidbody Collider | Kinematic Rigidbody Collider | Static Trigger Collider | Rigidbody Trigger Collider | Kinematic Rigidbody Trigger Collider | |
Static Collider | Y | Y | ||||
Rigidbody Collider | Y | Y | Y | |||
Kinematic Rigidbody Collider | Y | Y | Y | |||
Static Trigger Collider | Y | Y | Y | Y | ||
Rigidbody Trigger Collider | Y | Y | Y | Y | Y | Y |
Kinematic Rigidbody Trigger Collider | Y | Y | Y | Y | Y | Y |
References
- https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
- https://docs.unity3d.com/Manual/CollidersOverview.html