Introduction to collision detection in Unity

Collision detection is an essential element in game development. In Unity, whenever two objects interact, a collision occurs. The UnityEngine offers various ways of responding to collision events, whether by the use of Physics or by the custom C# scripts. 

To detect the collision between two GameObjects, Unity offers components called Colliders. 

GameObjects are the fundamental objects that represent characters, props, and all the objects inside a scene – every object in your game is a GameObject.

What are colliders?

Colliders are components which define the shape of a GameObject for physical collisions.

Colliders define the objects' physical boundaries to calculate collisions accurately.

Types of colliders

Unity offers different types of colliders each of which are given below.

  • Sphere Collider: It is a simple collider in the shape of a ball which is suitable for spherical objects.

  • Box Collider: It is a simple cuboid shape collider which is suitable for objects with box shapes.

  • Capsule Collider: This is a cylindrical shaped collider which has hemispherical ends. It is mostly used for character controllers.

  • Mesh Collider: It is a collider that matches the shape of the game object's mesh exactly. This collider type is useful for more complex shapes but comes at the expense of performance.

  • Terrain Collider: It is a collider which is specifically designed for the terrain objects.

Collision detection in Unity

Collision occurs whenever the two colliders interact. To detect this collision, you can either use Physics to control the objects' motion or scripts to call the functions related to the collision.

Key aspects of collision

Here are some of the key features of the collision system in Unity.

Collision response: The physics engine determines how the objects should respond when they collide. It usually involves a change in the speed and direction.
Bouncing back of a ball whenever it hits the wall is an example of collision response.

Collision events: There are many event functions in Unity which automatically get called whenever a collision occurs. These functions include onCollisionEnter(), OnCollisionStay(), and OnCollisionExit(). You can use these functions whenever the corresponding events happen.

Note: OnCollisionEnter can be used to decrease the player's health whenever the player collides with the enemy.

Collision layers and matrix: Unity offers different layers for GameObjects which you can set up to specify which layers can interact with each other. It helps to make sure that only the relevant collisions are detected.

How to detect collision

To detect collision between two colliders, you can make use of the collision detection functions mainly OnCollisionEnter(). It gets called as soon as the two GameObjects collide with each other.

A sample C# script is given below which outputs to the console as soon as the OnCollisionEnter() function is called.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Gets called at the start of the collision
void OnCollisionEnter(Collision collision)
{
Debug.Log("Entered collision with " + collision.gameObject.name);
}
// Gets called during the collision
void OnCollisionStay(Collision collision)
{
Debug.Log("Colliding with " + collision.gameObject.name);
}
// Gets called when the object exits the collision
void OnCollisionExit(Collision collision)
{
Debug.Log("Exited collision with " + collision.gameObject.name);
}
}

Explanation

  • Lines 1–3: These lines make all the necessary imports.

  • Line 5: A class named NewBehaviourScript is declared here which inherits from the MonoBehaviour class.

  • Lines 8–11: OnCollisionEnter() function is called whenever the GameObject enters the scene. It takes the collision object and returns the name of the GameObject it enters in collision with.

  • Lines 14–17: OnCollisionStay() function is called during the stay of the GameObject in the scene. It takes the collision object and returns the name of the GameObject it is colliding with.

  • Lines 20–24: OnCollisionExit() function is called whenever the GameObject exits the scene. It takes the collision object and returns the name of the GameObject it exited in collision with.

Demonstration

Using Colliders as Triggers

The scripts in Unity can detect whether collision occurs and returns the response actions using the OnCollisionEnter function. However, the physics engine can be used to detect whenever one collider enters the space of another collider without creating a collision.

A collider (on which the Is Trigger property is set) does not behave as a solid GameObject. It allows other colliders to pass through it. Whenever a collider enters the space of other GameObjects, the OnTriggerEnter() function gets called on the object.

Trigger response and events: Unity engine also offers trigger colliders which are used whenever a GameObject enters or exits the specified area. The main functions associated with the trigger events are OnTriggerEnter(), OnTriggerStay(), and OnTriggerExit(). These functions can be used whenever the corresponding events happen.

Note:

  • You will have to configure the Is Trigger property if you want the GameObjects to collide.

  • If you want your colliders to interact physically with the world, Is Trigger property should be unchecked.

  • If you want your collider to act as a trigger for an event when something enters it, Is Trigger property should be checked.

Example

You can define a response, such as increasing the player’s score, playing a sound, or displaying a message, whenever a trigger detects that the player has entered the specified area.

These responses can be implemented using C# scripts attached to the GameObjects.

A sample C# script is given below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Gets called when the object enters the collider area
void OnTriggerEnter(Collider objectName)
{
Debug.Log("Entered collision with " + objectName.gameObject.name);
}
// Gets called during the stay of object inside the collider area
void OnTriggerStay(Collider objectName)
{
Debug.Log("Colliding with " + objectName.gameObject.name);
}
// Gets called when the object exits the collider area
void OnTriggerExit(Collider objectName)
{
Debug.Log("Exited collision with " + objectName.gameObject.name);
}
}

Explanation

  • Lines 1–3: These lines make all the necessary imports.

  • Line 5: A class named NewBehaviourScript is declared here which inherits from the MonoBehaviour class.

  • Lines 8–11: OnTriggerEnter() function is called whenever the collider enters the specified area.

  • Lines 14–17: OnTriggerStay() function is called if the colliders are currently interacting.

  • Lines 20–24: OnTriggerExit() function is called whenever the Collider exits the scene. It takes the collider object and returns the name of the GameObject it exited colliding with.

Demonstration

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved