0
0
Unityframework~30 mins

Obstacle avoidance in Unity - Mini Project: Build & Apply

Choose your learning style9 modes available
Obstacle avoidance
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use transform.Rotate(0, turnSpeed * Time.deltaTime, 0); to turn and transform.Translate(Vector3.forward * speed * Time.deltaTime); to move forward.