I spent a couple of hours recently playing around with this top down 2D driving simulator in Unity and implemented a 2D Waypoint AI Car Driving system.
It’s been put together really nicely and implements most (if not all) of the physics detailed in this great Car Physics For Games post.
The only thing the implementation I found on GitHub is missing is an AI component that can ‘drive’ the normal, player controlled script.
Implementing a Waypoint System
I started off by adding a simple waypoint system.
This is as simple as adding a List<Transform>
for the waypoint nodes. In each car’s Update()
method I simply keep track of the index of the current waypoint in the list, and track the current distance to the next waypoint. There is a distance threshold that is checked constantly for the next waypoint. When this is reached, the waypoint is considered ‘reached’.
Steer Left Or Steer Right?
The next thing to tackle is for the AI to determine if it should be steering left or right. I’ve implemented this by creating a boolean value using the InverseTransformPoint of the AI car’s transform and the current target waypoint position.
transform.InverseTransformPoint(currentWaypointPos)
If the value is negative, then the next waypoint is to the left and the AI car should apply steering to the left. Otherwise, apply steering to the right.
Collision Checks
Finally I do a few raycast checks out the front of the vehicle to see if it is hitting any obstacles.
Physics2D.Raycast(frontBumperTransform.position, frontBumperTransform.up, frontCheckDistance)
If a hit is detected, then I ease off the throttle and set a flag to say that we are hitting an obstacle. If this flag is true, a value of -1 is multiplied to any steering values (left is -1 and right is -1) to counter steer, and reverse is engaged with a negative throttle value for a few moments.
This allows the AI car to stop, steer away from the obstacle and reverse out of the situation.
There are still many more improvements that could be made to this 2D waypoint AI car driving system. For example, smoothing out the steering behaviour. Currently the cars tend to ‘wiggle’ a bit as they oversteer each time they check if a waypoint is to the left of right.
For now though, it makes for a fun little game where multiple cars can be added to race against.