In my game, ranged units and melee units have the same behavior. Ranged units try to maintain a fixed distance r
, from their targets. If they're within r + d
of the target (where d
is a small value) they stop and shoot it. Note that this means the ranged unit can't be closer than r - d
. Melee units are the equivalent of ranged units, but with r
set to zero.
Right now, my AI for ranged units is as follows:
- Find a path to the target using A*.
- Walk along the path until you are within
[r - d, r + d]
of the target. - Stop and shoot. If the target is dead, quit.
- If you are still within
[r - d, r + d]
, goto 3. - Otherwise, move away/towards the target until you are within
r + d
again. Goto 4.
Here's a sort of diagram.
My problem is, if there are obstacles and the target moves, step 5
causes a lot of problems. Ranged units will end up backing into walls, unable to shoot. If instead of going to step 5
I go back to step 1
(planning a path), the problem still isn't solved, because walking toward the target will only decrease the range, not increase it.
How can I get ranged units to successfully follow and shoot their targets?