PDA

View Full Version : [AS2] Referencing closest enemy to a friendly AI


12Hits
08-31-2009, 02:38 PM
What's up everyone, how's it going. Got a bit of a problem I need sorting so here goes..

Basically, my game spawns various enemies dynamically (using a random script). These all use the instance name "zombie"+enemyvar so they can be attached at runtime. Now I need to know how I can calculate the enemy which is closest to my friendly AI person (x and y distance), and reference that one in the friendly's actionscript (ie. _root.somethingsomething).

All help is highly appreciated, hope I've written this clearly enough :confused:

12Hits
08-31-2009, 05:53 PM
Anybody please? :cool:

Greg SS
08-31-2009, 06:31 PM
function nearestZombie(x:Number, y:Number):Movieclip
{
var min:Number = Number.MAX_VALUE;
var dist:Number, index:Number;
var delta:Point = new Point();

for(i=0; i<zombies.length; i++){
delta.x = Math.abs(zombies[i]._x - x);
if(delta.x > min) continue;

delta.y = Math.abs(zombies[i]._y - y);
if(delta.y > min) continue;

dist = delta.length;
if(dist > min) continue;

min = dist;
index = i;
}

return zombies[i];
}

12Hits
08-31-2009, 07:48 PM
function nearestZombie(x:Number, y:Number):Movieclip
{
var min:Number = Number.MAX_VALUE;
var dist:Number, index:Number;
var delta:Point = new Point();

for(i=0; i<zombies.length; i++){
delta.x = Math.abs(zombies[i]._x - x);
if(delta.x > min) continue;

delta.y = Math.abs(zombies[i]._y - y);
if(delta.y > min) continue;

dist = delta.length;
if(dist > min) continue;

min = dist;
index = i;
}

return zombies[i];
}


Got some errors when I tried this..

'The class or interface 'Movieclip' could not be loaded.'
'The class or interface 'Point' could not be loaded.'

Greg SS
09-01-2009, 03:48 AM
add
import flash.geom.Point
and change Movieclip to MovieClip

12Hits
09-01-2009, 08:35 AM
add
import flash.geom.Point
and change Movieclip to MovieClip

It still doesn't seem to be working unfortunately..

So, let me get this straight - can I use this code on a Movie Clip's actions (inside an onClipEvent(enterFrame))?

Do I need to change any of the variables in the script like zombies or i? Because at present it doesn't look like the script actually references the instance names of my zombies.

I am calling the function, but if I try and trace zombies[i] right after, I constantly get undefined.

Greg SS
09-01-2009, 11:10 AM
I'm only giving you one of the concept of how it can be done.
I don't know how you set your game, you would have to adapt the code to your game yourself.

12Hits
09-01-2009, 01:43 PM
Oh right k I'll work with it. Thanks for the push in the right direction