0
0
Unityframework~7 mins

Obstacle avoidance in Unity

Choose your learning style9 modes available
Introduction

Obstacle avoidance helps a character or object move without bumping into things. It makes movement smooth and safe.

When a game character needs to walk around walls or objects.
When a robot in a simulation must not hit obstacles.
When an AI-controlled car drives on a track with barriers.
When a drone flies indoors avoiding furniture.
When a player-controlled object should not get stuck on obstacles.
Syntax
Unity
using UnityEngine;

public class ObstacleAvoidance : MonoBehaviour
{
    public float speed = 5f;
    public float rotationSpeed = 200f;
    public float detectionDistance = 2f;

    void Update()
    {
        if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, detectionDistance))
        {
            // Obstacle detected, turn away
            Vector3 avoidDirection = Vector3.Reflect(transform.forward, hit.normal);
            Quaternion targetRotation = Quaternion.LookRotation(avoidDirection);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }
        else
        {
            // No obstacle, move forward
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}

This script uses a raycast to detect obstacles in front of the object.

If an obstacle is detected within detectionDistance, the object turns away smoothly.

Examples
This example shows how to detect an obstacle directly ahead and instantly turn away.
Unity
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, detectionDistance))
{
    // Obstacle detected
    Vector3 avoidDirection = Vector3.Reflect(transform.forward, hit.normal);
    transform.rotation = Quaternion.LookRotation(avoidDirection);
}
This example smoothly rotates the object away from the obstacle instead of snapping instantly.
Unity
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, detectionDistance))
{
    // Smooth turning to avoid obstacle
    Vector3 avoidDirection = Vector3.Reflect(transform.forward, hit.normal);
    Quaternion targetRotation = Quaternion.LookRotation(avoidDirection);
    transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
If no obstacle is detected, the object moves forward at a constant speed.
Unity
// No obstacle detected
transform.Translate(Vector3.forward * speed * Time.deltaTime);
Sample Program

This complete Unity script moves an object forward. It uses a raycast to check for obstacles ahead. If it finds one, it turns away smoothly. It also draws a red debug ray in the scene view to show the detection line and prints messages to the console.

Unity
using UnityEngine;

public class ObstacleAvoidance : MonoBehaviour
{
    public float speed = 5f;
    public float rotationSpeed = 200f;
    public float detectionDistance = 2f;

    void Update()
    {
        Debug.DrawRay(transform.position, transform.forward * detectionDistance, Color.red);

        if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, detectionDistance))
        {
            Debug.Log("Obstacle detected: " + hit.collider.name);
            Vector3 avoidDirection = Vector3.Reflect(transform.forward, hit.normal);
            Quaternion targetRotation = Quaternion.LookRotation(avoidDirection);
            transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }
        else
        {
            Debug.Log("No obstacle, moving forward");
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}
OutputSuccess
Important Notes

Time complexity: O(1) per frame because raycast checks one direction.

Space complexity: O(1) as no extra data structures are used.

Common mistake: Not normalizing direction vectors or forgetting to set the detection distance.

Use obstacle avoidance when you want smooth, automatic turning around obstacles. For complex paths, consider pathfinding algorithms instead.

Summary

Obstacle avoidance helps objects move without hitting things.

It uses raycasts to detect obstacles ahead.

The object turns away smoothly when it detects an obstacle.