Get Nearest (enemy) Object

This is something I do in flash quite often.
I need to get the enemy that ist nearest to the hero.

so I iterate through the enemy array and sort it.
in the end the nearest enemy is the first item in my array:

actionscript:
[as]
for(var i = 0; i < enemyArray.length; i++){

var enemy:Object = enemyArray[i]; // create a local object

// helper function that returns a distance value
enemy.theDistance = calcDist (hero, enemy)

// sort the array using the enemy object’s distance parameter
enemyArray.sortOn(“theDistance”, Array.NUMERIC);
}
[/as]

any idea how to port that to corona/LUA?

thanks in advance
-finefin
[import]uid: 70635 topic_id: 18973 reply_id: 318973[/import]

http://lua-users.org/wiki/LuaSorting [import]uid: 12704 topic_id: 18973 reply_id: 73063[/import]

if you get this working, can you please make a sample code or something? i think this will be great addition to “code sharing”)
[import]uid: 16142 topic_id: 18973 reply_id: 73070[/import]

in fact, that function IS working. :slight_smile:
it will also be part of my game helper module I will share eventually…

-finefin [import]uid: 70635 topic_id: 18973 reply_id: 73077[/import]

hm… thanks.
but I still haven’t found what I’m looking for (insert cheesy 80s music here).
so I had to think of another way:

getNearest = function (obj1, enemyTable)  
  
 local obj1 = obj1  
 if #enemyTable == 0 then return end -- it's empty? oops!  
  
 local nearest -- will track the nearest object  
 local theDistance = 5000 -- once upon a time in a galaxy far, far away  
  
 for i,val in pairs(enemyTable) do  
 local d = distanceBetween (obj1, val.object)  
 if d \< theDistance then -- closer than planet endor?  
 theDistance = d -- new distance  
 nearest = val.object -- nearest object so far - iterate more!  
 end   
 end  
  
 return nearest  
end  

if anyone has a better idea, please tell me :slight_smile:

-finefin [import]uid: 70635 topic_id: 18973 reply_id: 73066[/import]

good work then, i can assume that it will be extremely helpful for someone [import]uid: 16142 topic_id: 18973 reply_id: 73079[/import]