Game Development Reference
We need to switch to the Vehicle.vb file to get the vehicles to think. The AI will
need a variety of helper functions. The AI is interested in what vehicle is ahead of
or behind it. The vehicles also have a limit to how hard they can accelerate. That
limit allows high acceleration from low speed and lower acceleration when the
vehicle is near its desired speed. The formula used is a simplification of actual
acceleration curves. As you might expect, trucks have too much low-end pickup,
and the exotic vehicles have too much high-speed charge. That said, even this
token nod toward realism gives the right impression. Add the following code to
the Vehicle class:
'Institute acceleration limits.
Public Function BestNextSpeed() As Integer
'Acceleration drops with speed.
Dim a As Integer = CInt(0.1 * (2 * myDesiredSpeed - currentV))
'But even the slowest truck can do 1.
If a < 1 Then a = 1
Dim newV As Integer = currentV + a
'Don't go faster than desired.
If newV > myDesiredSpeed Then newV = myDesiredSpeed
'Who is ahead of me in a given lane?
Private Function CarAhead(ByVal desiredLane As Integer, _
ByVal myIndex As Integer, ByVal theRoad As Road) As Vehicle
Dim i As Integer
Dim OtherGuy As Vehicle
For i = myIndex + 1 To theRoad.ToyBox.Count
'Ahead of me in the lane we are checking.
OtherGuy = CType(theRoad.ToyBox(i), Vehicle)
If OtherGuy.Lane = desiredLane Then
'Who is behind me in a given lane?
Private Function CarBehind(ByVal desiredLane As Integer, _