Course contentsShow
← Unity Game Development
Lesson 159 of 8283. Physics and InteractionFree lesson

Handling Physical Impacts with OnCollisionEnter

Develop scripts that respond to solid object impacts by calculating collision points and applying logic based on physical contact.

In this lesson, you will learn how to trigger specific game logic, such as sound effects or damage calculations, the exact moment two solid objects physically strike one another.

Understanding OnCollisionEnter

While OnTriggerEnter is used for overlapping zones that objects pass through, OnCollisionEnter is specifically designed for physical impacts. In Unity, this method is called automatically by the physics engine when a Collider attached to your GameObject makes contact with another Collider, provided at least one of the objects has a Rigidbody component attached.

The method provides you with a Collision object as a parameter, which acts as a data packet containing crucial information about the impact, such as the contact point in world space and the velocity of the impact.

Implementing a Basic Impact Script

To use this, simply define the OnCollisionEnter method within your script. Here is a simple example that logs where the collision occurred:

using UnityEngine;

public class ImpactHandler : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        // Accessing the first point of contact
        ContactPoint contact = collision.contacts[0];
        
        Debug.Log("Impact detected at: " + contact.point);
        
        // You can also check what you hit using tags
        if (collision.gameObject.CompareTag("Enemy"))
        {
            Debug.Log("Hit an enemy! Applying recoil force.");
        }
    }
}

Why it Matters

Using OnCollisionEnter allows your game to feel tactile. Instead of just having objects pass through each other, you can use the data within the Collision parameter to create dynamic gameplay. For example, by checking collision.relativeVelocity, you can decide if the hit was hard enough to trigger a "shatter" animation or a heavy impact sound. Because this happens within the Unity physics simulation pipeline, you are guaranteed that the interaction is handled at the correct moment in the frame, keeping your physics interactions consistent and reliable.

Key Takeaway: Use OnCollisionEnter to execute logic during solid impacts, utilizing the Collision parameter to retrieve precise data about the contact point and the velocity of the colliding objects.