How to Make an Object Avoid Obstacles

Hello!
This is my first time posting here, so I want to start off by saying I am completely new to Unity and C#, so I apologize if I don’t understand basic terminology or how to do simple coding. I’m still learning!

I just finished taking a SkillShare course teaching how to code in Unity using C#. We created a very simple 2D endless racing game where the player controls a car and avoids obstacles to try to get as far as they could without crashing.

At the end of the class, I decided I wanted to try and figure out how to add a computer controlled car for the player to race against. I’m currently trying to figure out how to get that car to avoid obstacles. I’ve given them a rigidbody2D and a box collider which is bigger than the car itself so it has time to detect the object and move before it hits it. Here’s part of the script I created:

private void OnTriggerEnter2D(Collider2D collision)
{
     CarDirection = Random.Range(1, 3);
   
     if (CarDirection <= 1)
     {
          rb.AddForce(new Vector2(-5 * speed, 0));
     }
     else if (CarDirection >= 2)
     {
          rb.AddForce(new Vector2(5 * speed, 0));
     }
}

The idea is that whenever an object enters the cars collider, it will generate a random number, either 1 or 2, and go in the direction that corresponds with that number. 1 = left, 2 = right. In my mind, I thought that would be enough to allow it to avoid the obstacles.

And this works…sorta… but it’s super clunky and honestly makes the car act weird and unnatural… Is there a way to improve this code, or something else I can do that would be easier/more efficient?

If you need any more information, just let me know.
Thanks!

I don’t think your algorithm will really be good at obstacle avoidance…

Try out Unity’s NavMesh! It’s made specifically for pathfinding. Here’s a good tutorial: