📖 Scenario: You are creating a simple Unity game where a character moves forward and avoids obstacles automatically.Imagine a small robot that moves straight but stops or turns when it senses an obstacle in front.
🎯 Goal: Build a Unity script that makes a game object move forward and avoid obstacles by detecting them with a raycast and turning away.
📋 What You'll Learn
Create a float variable called speed with value 5f
Create a float variable called turnSpeed with value 90f
Use Physics.Raycast to detect obstacles in front within 2f distance
If an obstacle is detected, rotate the object to the right using transform.Rotate
If no obstacle is detected, move the object forward using transform.Translate
💡 Why This Matters
🌍 Real World
Obstacle avoidance is used in games and robotics to help characters or robots move safely without hitting objects.
💼 Career
Understanding obstacle detection and movement control is important for game developers and robotics programmers working on AI navigation.
Progress0 / 4 steps
1
Create movement speed variables
In a new C# script, create two float variables called speed and turnSpeed. Set speed to 5f and turnSpeed to 90f.
Unity
Hint
Use public float speed = 5f; and public float turnSpeed = 90f; inside the class.
2
Add obstacle detection distance
Add a float variable called obstacleDistance and set it to 2f to define how far the raycast will check for obstacles.
Unity
Hint
Define public float obstacleDistance = 2f; inside the class.
3
Detect obstacles with raycast
Inside the Update() method, use Physics.Raycast from the object's position forward to check if an obstacle is within obstacleDistance. Use if (Physics.Raycast(transform.position, transform.forward, obstacleDistance)).
Unity
Hint
Use Physics.Raycast(transform.position, transform.forward, obstacleDistance) inside Update().
4
Move forward or turn to avoid obstacle
Complete the Update() method so that if an obstacle is detected, the object rotates right by turnSpeed * Time.deltaTime. Otherwise, it moves forward by speed * Time.deltaTime. Use transform.Rotate(0, turnSpeed * Time.deltaTime, 0) and transform.Translate(Vector3.forward * speed * Time.deltaTime).
Unity
Hint
Use transform.Rotate(0, turnSpeed * Time.deltaTime, 0); to turn and transform.Translate(Vector3.forward * speed * Time.deltaTime); to move forward.
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
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 A
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
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 C
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
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 D
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:
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
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 B
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
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 A
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 unknownstrongwhile earning +1 Grip toward your certificate.