# Opponent car logic in race games

I'm developing a race game in Andengine. I have created a car which player is controlling. But since this is a race game, there should be 3 or 4 car which snatch with the player's car. My question is: How do the opponent cars move along the path? How their logic works? Must I know certain path?

-

I outline one simple implementation:

Assume your track is a series of points joined together and the last point joins the first to form a cicular track.

loop through all the points and find the nearest point to your car. Take this point and minus the previous point to get a normalized track forward vector; take the car position minus the previous point to get a "car vector"; do a dot product to get the perpendicular distance from the track vector.

The perpendicular distance represents how far away the car is from the center of the track. Now you know the distance and on which side of the track the car is on, you can steer (change the rotation/direction) the car back onto the track.

-

In racing games it's often best to use both track relative coordinates as well as Cartesian world coordinates. This makes it easier to reason about overtaking and optimal lines the cars should follow.

A great article to read would be Shawn Hargreaves' postmortem on the MotoGP AI

You can also try to use follow and flock algorithms like Open Steer

If you are more interested in how to determine the optimal curve that (AI) drivers should follow on a track you could research flow fields. You can find more info about those in the links in this answer on this same website.

-