Unity Cookbook. Collision
Collision
Colliders
- Manual: Colliders overview
- Colliders allow for interacting with other GameObjects
- The “hitbox” of the GameObject
- Usually simpler in geometry than the GameObject itself
- CapsuleCollider(2D), BoxCollider(2D), PolygonCollider2D…
- Extra: To show colliders in play mode:
- Project Settings > Physics(2D) > Gizmos > Always Show Colliders
- In Play mode, enable Gizmos button
Collision events
OnCollisionEnter
/OnCollisionEnter2D
- when collision with another collider starts
OnCollisionStay
/OnCollisionStay2D
- called every frame a collider is in contact
OnCollisionExit
/OnCollisionExit2D
- when collision with another collider ends
- See the links for code examples!
- Note: To make the collision happen, at least one of the colliding GameObjects has to have a RigidBody component attached to it!
Triggers
- Normally, Unity initiates actions using the
OnCollisionEnter
function - If collider
IsTrigger
, then it does not stop other colliders, but only detects if something collides with it - noOnCollisionEnter
!- Collision functions are replaced with
OnTriggerEnter
,OnTriggerExit
,OnTriggerStay
- Guess the 2D versions…
- Collision functions are replaced with
- Note: If a trigger is colliding with another trigger,
OnTriggerEnter
gets called twice per collision!
Collider2D vs Collision2D
- Trigger callback functions use
Collider2D
class as their argument - Collision callback functions use
Collision2D
class- Collider can actually be found inside the Collision2D class: access it with
.collider
- Collider can actually be found inside the Collision2D class: access it with
- Most importantly: for both classes, you can access the corresponding gameObject with
.gameObject
Extra: Checking collision in Update
- The callback functions are handy, but sometimes you want to check collision inside an update function
- For that, you need the overlap collider
Exercise 1. Collectibles
Continue with the Player character from the Input exercise.
Add multiple collectible GameObjects to the scene.
When the player character collides with a collectible, destroy it and add one to Player’s internal counter of collected items.
Exercise 2. Colliding with moving obstacles
Continue previous exercise. Add moving objects to the scene that block the player’s way.
If the player collides with them, make the player bounce off of them!