Bird
Raised Fist0
Unityframework~7 mins

Obstacle avoidance in Unity

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of obstacle avoidance in Unity game programming?
easy
A. To help objects move without hitting obstacles
B. To make objects jump higher
C. To change the color of objects
D. To increase the speed of objects

Solution

  1. Step 1: Understand obstacle avoidance concept

    Obstacle avoidance is used to prevent objects from colliding with obstacles in their path.
  2. Step 2: Identify the correct purpose

    The main goal is to help objects move smoothly without hitting anything.
  3. Final Answer:

    To help objects move without hitting obstacles -> Option A
  4. Quick Check:

    Obstacle avoidance = prevent collisions [OK]
Hint: Obstacle avoidance means avoiding collisions [OK]
Common Mistakes:
  • Confusing obstacle avoidance with speed control
  • Thinking it changes object appearance
  • Assuming it makes objects jump
2. Which Unity function is commonly used to detect obstacles ahead for avoidance?
easy
A. Update
B. Instantiate
C. Raycast
D. Destroy

Solution

  1. Step 1: Recall Unity functions for detection

    Raycast is used to send an invisible line to detect objects in front.
  2. Step 2: Match function to obstacle detection

    Raycast detects obstacles ahead, while Instantiate creates objects, Update runs every frame, and Destroy removes objects.
  3. Final Answer:

    Raycast -> Option C
  4. Quick Check:

    Obstacle detection = Raycast [OK]
Hint: Raycast checks ahead for obstacles [OK]
Common Mistakes:
  • Choosing Update which runs every frame but doesn't detect
  • Confusing Instantiate with detection
  • Selecting Destroy which deletes objects
3. What will be the output if the following Unity C# code runs and an obstacle is detected by the raycast?
void Update() {
    if (Physics.Raycast(transform.position, transform.forward, out var hit, 5f)) {
        transform.Rotate(0, 90, 0);
        Debug.Log("Obstacle detected, turning right.");
    } else {
        transform.Translate(Vector3.forward * Time.deltaTime * 3);
    }
}
medium
A. The object moves forward continuously without turning
B. The object moves backward
C. The object stops moving and no message is logged
D. The object turns right and logs "Obstacle detected, turning right."

Solution

  1. Step 1: Analyze raycast detection and response

    If the raycast hits an obstacle within 5 units, the object rotates 90 degrees on Y axis and logs a message.
  2. Step 2: Understand else behavior

    If no obstacle is detected, the object moves forward at speed 3 units per second.
  3. Final Answer:

    The object turns right and logs "Obstacle detected, turning right." -> Option D
  4. Quick Check:

    Obstacle detected = turn right + log message [OK]
Hint: If raycast hits, rotate and log; else move forward [OK]
Common Mistakes:
  • Ignoring the rotation when obstacle detected
  • Thinking object stops instead of turning
  • Assuming object moves backward
4. Identify the error in this obstacle avoidance code snippet:
void Update() {
    if (Physics.Raycast(transform.position, transform.forward, 5f)) {
        Debug.Log(hit.distance);
        transform.Rotate(0, 90, 0);
    }
}
medium
A. The Rotate method parameters are incorrect
B. The Raycast method is missing the 'out RaycastHit' parameter
C. The if condition should use '==' instead of parentheses
D. The Update method should be named FixedUpdate

Solution

  1. Step 1: Check Raycast method signature

    Physics.Raycast requires an 'out RaycastHit' parameter to store hit info when using this overload.
  2. Step 2: Verify Rotate and method names

    Rotate parameters are correct for rotation; Update is valid for frame updates.
  3. Final Answer:

    The Raycast method is missing the 'out RaycastHit' parameter -> Option B
  4. Quick Check:

    Raycast needs 'out RaycastHit' [OK]
Hint: Raycast needs 'out RaycastHit' to detect hits [OK]
Common Mistakes:
  • Omitting the out parameter in Raycast
  • Confusing Rotate parameters
  • Thinking Update must be FixedUpdate
5. You want your Unity object to avoid obstacles smoothly by turning gradually instead of instantly. Which approach should you use in your obstacle avoidance script?
hard
A. Use Quaternion.Slerp to rotate smoothly when obstacle detected
B. Use transform.Rotate(0, 90, 0) instantly on detection
C. Stop the object completely when obstacle is detected
D. Ignore obstacles and keep moving forward

Solution

  1. Step 1: Understand smooth rotation methods

    Quaternion.Slerp smoothly interpolates rotation over time, creating gradual turns.
  2. Step 2: Compare with instant rotation

    transform.Rotate(0, 90, 0) turns instantly, which is not smooth.
  3. Final Answer:

    Use Quaternion.Slerp to rotate smoothly when obstacle detected -> Option A
  4. Quick Check:

    Smooth turn = Quaternion.Slerp [OK]
Hint: Use Quaternion.Slerp for smooth turning [OK]
Common Mistakes:
  • Using instant rotation causing jerky movement
  • Stopping object instead of turning
  • Ignoring obstacles completely
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard