Part 9 - Incoming!
Copy and paste the code below into Form1
- Private Sub MoveFlies()
- Randomize(Now.Ticks)
- For Each F As Fly In mobjFlies
- Dim NX, NY As Single
- Displacement(F.Position.X, F.Position.Y, F.Speed, F.Direction, NX, NY)
- If NX > Me.ClientSize.Width - 1 Then F.Direction += CSng(Rnd() * Math.PI)
- If NX < 0 Then F.Direction += CSng(Rnd() * Math.PI)
- If NY > Me.ClientSize.Height - 1 Then F.Direction += CSng(Rnd() * Math.PI)
- If NY < 0 Then F.Direction += CSng(Rnd() * Math.PI)
- F.Position.X = CInt(NX)
- F.Position.Y = CInt(NY)
- Dim FoundScent As Boolean = False
- For Each R As Receptor In F.Receptors
- Displacement(F.Position.X, F.Position.Y, R.Distance, R.Direction +F.Direction, NX, NY)
- For Each S As Scent In mobjScents
- If CircleCircle(S.Position.X, S.Position.Y, S.Strength, NX, NY,R.Distance) Then
- F.Direction += R.Direction
- ' Try using this line instead
- 'F.Direction += ((R.Direction * 0.9F) + (Rnd() * (R.Direction * 0.2F)))
- FoundScent = True
- Exit For
- End If
- Next
- Next
- If Not FoundScent Then F.Update()
- Next
- End Sub
Finally after all that setup we can begin to code some AI. The
MoveFlies method is at the heart of this application. First it re-seeds
the random number generator, and then begins to process each of the
flies in the flies collection.
The NX and NY variables are used to store the
next location that the fly will be moving to. A call to the
Displacement method is made and stores the new fly position in the NX
and NY variables. If the new position is outside of the bounds of the
form then a new random direction is given to the fly so that it does
not try to constantly escape from view.
The FoundScent
variable will store weather or not a scent was detected by a receptor.
It then proceeds to process each receptor. To determine the location of
the receptor on screen a call is made to the Displacement method again.
Now that the location of the receptor is known it begins to check each
scent in an effort to determine if the receptor collides with it. To
determine if a collision takes place a call to the CircleCircle method
is made.
The next line of code is how the fly knows what direction to move to, and how it is able to fallow a trail of scent objects.
- F.Direction += R.Direction
It
takes the direction the fly is currently facing and adds the direction
that the receptor is facing. Because the direction of the receptors are
relative the fly will then be facing in the general direction of the
scent.
Now that a scent has been detected we can set the FoundScent variable to true and exit the scent checking loop.
After
all receptors have been processed it checks if a scent was found and if
so calls the flies update method. The Fly.Update method checks to see
if the fly has changed direction within the last half second, and if
not changes the flies direction to a new random direction.