PDA

View Full Version : Find in range and closest.



Chesso
04-06-2013, 12:26 AM
I know a way it could be done (looping and checking against X, Y positions and finally narrowing it down) but looking to see if there are better or cleaner looking methods.

I have a defense mechanism with a certain range (let's say a 75 pixel radius), and I want it to react to enemies that come within that range, but I want the reaction to be biased
(the closest one to the mechanism for example), so it follows it until something else comes into a closer range.

It's probably not the nicest method but all my elements are array records (defenses, enemies etc), so I track all their data.

SilverWarior
04-06-2013, 02:05 AM
Here is and idea which might work. I havent used it yet.

How acurate must your range detection be. Do you need for your weapon to change to other target as soon as it is one pixel closer or would lets say 5 pixel distance variation be enough.
If it is the later then I sugest next aproach:
Make yourself several concentric circle sprites ranging from verry small to the size of maximum weapons range. You then position theese sprites so that they are centered on your weapon.
Finally you simply use colision detection, starting with smalest sprite and if there is no colision with enemy unit you continue with larger ones until you manage to get first enemy in range.
On another thought you should first check colision detection with largest one (representing maximum weapons range) and only then use previously mentioned aproach to find closest one.

laggyluk
04-06-2013, 06:38 AM
i think in any case you need to check against all the enemies.
something like this:


indexOfClosest:=-1;
closest:=Infinity;
for i:=0 to length(enemies)-1 do begin
d:=distance(player,enemies[i]);
if (d<closest) and (d<=inRange) then begin
indexOfClosest:=i;
closest:=d;
end;
end;