Unity Collision 2D and 3D: Super Simple Guide

Collision detection is required for all types of games and is one of the major components to know if you want to learn Unity. Unity Collision works based on the collider component that can be added to any game object. Also, you need to understand how colliders and Unity Rigidbody work together to efficiently use them.

Without a basic understanding of how Unity colliders work, it will be very difficult to code the game mechanics. In this post, we will see how to use colliders in Unity and where to use OnCollisionEnter and OnTriggerEnter functions.

Introduction to Unity Colliders

A Collider in Unity, defines the boundary of a game object. The shape of the collider is depended on the type of collider used. Colliders can also be classified with respect to physics, depending on how they interact with other objects.

Also, Unity has divided the colliders into 2D and 3D. So, you have to be very careful which collider you are using. All your codes and collision detection will change to 2D and 3D.

Unity Collider Types based on Physics

Static collider

Static colliders are considered to be non-moving objects by Unity. Do not confuse static game object with the static collider. If a Rigidbody is not attached to a collider then it’s a static collider. They do not move when an object Collides to with them. Though, they can be moved using transform.

Rigidbody collider or Dynamic Collider

A Rigidbody collider works like a real-world object. It is governed by the forces of physics. If you apply force on it, it will move. In Unity, Rigidbody is used on an object which needs to be affected by physics laws.

Kinematic Rigidbody collider

A kinematic Rigidbody collider is a Rigidbody that behaves like a static object but can be converted into a dynamic collider at point of the game.

3D collider shapes in Unity

Collider shapeWhere to useEffect on Performance
Box ColliderObject shaped like cubeLess Performance intensive
Sphere Collider3D round shaped objectsLess Performance intensive
Capsule CollidersFor CharactersLess Performance intensive
Mesh CollidersObjects with Uneven shapesPerformance intensive
Terrain CollidersFor Unity terrainsVery Performance intensive

Adding a 3D collider in Unity

To add a collider to your game object, select the object in Hierarchy view and click on Add Component in the Inspector window. Then select the type of Collider based on your requirement.

You can adjust the size of the collider using the Edit Collider button.

Unity Collider component add to a game object.

Non-trigger and Trigger collider

In Unity you can mark a collider as trigger using the check box in the inspector window. The behavior of the object changes if it is marked as a trigger.

Non-trigger Colliders

When a collider is not marked as Trigger, Unity will detect a collision only if one of the objects is a Rigidbody. That is, if you have two game object marked as static colliders then collision between them will not be detected.

It’s the same case with two kinematic Rigidbodies. Find the collision matrix for non-trigger Unity colliders in the image below.

collision matrix for Non trigger unity colliders

Ref: Unity docs

On Collision Enter Function

To detect the collision, we can use the OnCollisionEnter(). This function is called when a collision between non-trigger colliders is detected.

The function contains all details of the collision. You can get the following details for the collision variable.

Properties of OnCollisionEnter()Description
colliderThe Collider that was hit.
contactCountNumber of contacts for this collision.
gameObjectThe collider game object
relativeVelocityThe relative linear velocity of the two colliding objects.
rigidbodyThe Rigidbody attached to the collider.
transformThe Transform of the object we hit.

Along with the above properties, there are two more functions that we can access. One is GetContact and the other is GetContacts.

GetContact returns a single point from the contacts array and GetContacts returns an array of all contact points.

Here is an example code on how to use OnCollisionEnter() to destroy the object that we hit, if it has an Enemy tag.

void OnCollisionEnter(Collision col)
{
        If(col.gameObject.tag=="Enemy")
           {
            Destroy(col.gameObject)
           }
}

Unity Trigger collider

When you mark a collider as a trigger, it no longer behaves like a solid object. It allows the other object to pass through it. But the time of one object entering another object’s space can trigger a function. With that, you can know if a collision has happened without actually creating a collision. A trigger collider can collide with a kinematic Rigidbody. Here is the collision matrix for trigger colliders.

Trigger collision matrix

On Trigger Enter function

Trigger collision doesn’t work in Unity if both the colliders are static colliders. In all the other cases the OnTriggerEnter function is called. Unlike OnCollisionEnter, you cannot get the collision parameters in this case. But there are some properties that you can use.

gameObjectThe game object that we hit
tagThe tag of the game object that we hit.
transformThe Transform of Game Object that we hit.
nameThe name of the Game Object that we hit.

Here is an example of how to use OnTriggerEnter to destroy the object that we hit, if it has an Enemy tag.

void OnTriggerEnter(Collider col)
{
        If(col.tag=="Enemy")
        {
            Destroy(col.gameobject)
        }
 }

Summarizing collision matrix

If you did not understand the matrix completely then here is a simple comparison to help you. Consider static colliders as objects that don’t move like walls. Rigidbody collider denotes a moving object like a ball. Kinematic Rigidbody denotes that the object is not moved by physics but can be moved by script or animation.

Unity does not want to detect collision between two static objects. So normally, collision is detected only if one of the game objects is movable by physics. Whereas trigger function works little differently. It works only if one of the colliders is marked as trigger and both objects are not static.

Setting Collision Layers in Unity

One you have added your colliders and Rigidbody now it’s time to set the layers. Unity gives you control to decide which layers collide with each other.

This setting is available in Edit>Project settings> Physics.

Layer collision setting in Unity

You can just uncheck the layers that you don’t want to collide with. For example, if you don’t want the friend layer to collide with the water layer. Then just uncheck the box in water row of the Friend column.

Remember to create all your layers first before editing this setting.

Other Unity Collider functions

There are few more functions to detect whether the game object has exited the collision phase or its still colliding with another object.

Non-Trigger Collision

  • OnCollisionExit– Is called when the Collider exits a Collision.
  • OnCollisionStay – Is called when the Collider is still colliding with another object.

Trigger Collision

  • OnTriggerExit– Is called when the Trigger Collider exits a Collision.
  • OnTriggerStay– Is called when the Trigger Collider is still colliding with another object.

Unity Collision Detection 2D

Collision in 2D is very similar to 3D, but there is a change in terminology. When it comes to 2D, Unity has put in a lot of effort to distinguish 2D colliders from 3D.

2D Collision in Unity uses Physics2D engine. Everything in Physics2D has a suffix 2D added to it. It’s a physics engine on its own but for the 2D world.

Adding a 2D collider

Select your game object and click on Add Component in the inspector window. Add a 2D collider from the component list.

3D vs 2D collider Terminologies

3D collider2D Collider
OnCollisionEnterOnCollisionEnter2D
OnTriggerEnterOnTriggerEnter2D
OnCollisionExitOnCollisionExit2D
OnTriggerExitOnTriggerExit2D
OnCollisionStayOnCollisionStay2D
OnTriggerStayOnTriggerStay2D
ColliderCollider2D
CollisionCollision2D
RigidbodyRigidbody2D
BoxColliderBoxCollider2D
MeshColliderPolygonCollider2D
SphereColliderCircleCollider
CapsuleColliderCapsuleCollider2D
TerrainColliderEdgeCollider2D or TilemapCollider2D
WheelColliderCircleCollider2D

2D Collision layer setting in Unity

Similar to 3D you can decide which layers will collide with each other in physics 2D.

To set this you have to go to Edit>Project settings>Physics2D.

Layer Collision matrix 2D

Functions in Unity Collision 2D

OnCollisionEnter2D

This can be used to detect collision between two colliders that are not set as Trigger and at least one of them has a Rigidbody attached to it.

Syntax

void OnCollisionEnter2D(Collision2D col)
{
//Your code
}

OnTriggerEnter2D

OnTiggerEnter2D is used to detect collision between 2D colliders that are set as a trigger. You need to use this, even if one of the Collider is set as Trigger.

Syntax

void OnTriggerEnter2D(Collider2D col)
{
//Your Code
}

Other Unity 2D collider functions

Non-Trigger 2D Collision

  • OnCollisionExit2D- Is called when the Collider2D exits a Collision.
  • OnCollisionStay2D – Is called when the Collider2D is still colliding with another object.

Trigger 2D Collision

  • OnTriggerExit2D- Is called when the Trigger Collider2D exits a Collision.
  • OnTriggerStay2D- Is called when the Trigger Collider2D is still colliding with another object.

Sample script for 2D collision detection functions

using UnityEngine;

public class collision_test : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D col)
    {
        Debug.Log(" Non-trigger Colliders entering Collision");

    }
    void OnCollisionStay2D(Collision2D col)
    {
        Debug.Log(" Non -trigger Colliders in Collision");
    }

    void OnCollisionExit2D(Collision2D col)
    {
        Debug.Log("Non-Trigger Colliders existing collision");
    }
    void OnTriggerEnter2D(Collider2D col)
    {
        Debug.Log(" trigger Colliders entering Collision");

    }
    void OnTriggerStay2D(Collider2D col)
    {
        Debug.Log(" trigger Colliders in Collision");
    }

    void OnTriggerExit2D(Collider2D col)
    {
        Debug.Log("Trigger Colliders existing collision");
    }

}

That summarizes the collider function in Unity. If you have any questions, you can post it in the comment box below. Next, we will learn how to add components using scripts.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading