Obstacle avoidance helps a character or object move without bumping into things. It makes movement smooth and safe.
Obstacle avoidance in 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.
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);
}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);
}// No obstacle detected transform.Translate(Vector3.forward * speed * Time.deltaTime);
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.
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); } } }
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.
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
Solution
Step 1: Understand obstacle avoidance concept
Obstacle avoidance is used to prevent objects from colliding with obstacles in their path.Step 2: Identify the correct purpose
The main goal is to help objects move smoothly without hitting anything.Final Answer:
To help objects move without hitting obstacles -> Option AQuick Check:
Obstacle avoidance = prevent collisions [OK]
- Confusing obstacle avoidance with speed control
- Thinking it changes object appearance
- Assuming it makes objects jump
Solution
Step 1: Recall Unity functions for detection
Raycast is used to send an invisible line to detect objects in front.Step 2: Match function to obstacle detection
Raycast detects obstacles ahead, while Instantiate creates objects, Update runs every frame, and Destroy removes objects.Final Answer:
Raycast -> Option CQuick Check:
Obstacle detection = Raycast [OK]
- Choosing Update which runs every frame but doesn't detect
- Confusing Instantiate with detection
- Selecting Destroy which deletes objects
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);
}
}Solution
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.Step 2: Understand else behavior
If no obstacle is detected, the object moves forward at speed 3 units per second.Final Answer:
The object turns right and logs "Obstacle detected, turning right." -> Option DQuick Check:
Obstacle detected = turn right + log message [OK]
- Ignoring the rotation when obstacle detected
- Thinking object stops instead of turning
- Assuming object moves backward
void Update() {
if (Physics.Raycast(transform.position, transform.forward, 5f)) {
Debug.Log(hit.distance);
transform.Rotate(0, 90, 0);
}
}Solution
Step 1: Check Raycast method signature
Physics.Raycast requires an 'out RaycastHit' parameter to store hit info when using this overload.Step 2: Verify Rotate and method names
Rotate parameters are correct for rotation; Update is valid for frame updates.Final Answer:
The Raycast method is missing the 'out RaycastHit' parameter -> Option BQuick Check:
Raycast needs 'out RaycastHit' [OK]
- Omitting the out parameter in Raycast
- Confusing Rotate parameters
- Thinking Update must be FixedUpdate
Solution
Step 1: Understand smooth rotation methods
Quaternion.Slerp smoothly interpolates rotation over time, creating gradual turns.Step 2: Compare with instant rotation
transform.Rotate(0, 90, 0) turns instantly, which is not smooth.Final Answer:
Use Quaternion.Slerp to rotate smoothly when obstacle detected -> Option AQuick Check:
Smooth turn = Quaternion.Slerp [OK]
- Using instant rotation causing jerky movement
- Stopping object instead of turning
- Ignoring obstacles completely
Ready to prove it?
Pass the test and this pattern moves unknown
