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

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 - no OnCollisionEnter!
  • 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
  • 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!