In python you would have a list of enemies (gameObj) and sort it by distance ( closest to furthest ).
Then make the active target to be the listOfEnemy[0] (first in list/closest enemy).
def track(cont):
own = cont.owner
scene = own.scene
track_to = cont.actuators['track_to']
ai = [x for x in scene.objects if 'track_to' in x]
dist = [own.getDistanceTo(x) for x in ai]
if len(ai) != 0:
pair = min(zip(dist, ai))
track_to.object = pair[1]
cont.activate(track_to)
Wow,@BluePrintRandom, that is a lot worse.
Why would you think that is better?
Almost what I imagined!
Sorting this way would shorten the code and teach crucial part of using python built in sorting.
closest = sorted(ai, key=lambda enemy: own.getDistanceTo(enemy))
Second idea would be to use the near sensor’s like RockyMadio, which neat,
but having less bricks and more control over distance calculation (A* path len) is neater.
Ok thats easier, and check distance isn’t that hard to put into, also we can let it stop tracking.
So this is what you get:
# always -> python-module-track_to_closest.track-> edit object - trackto# use a property "track_distance" on the object using this script
def track(cont):
own = cont.owner
scene = own.scene
track_to = cont.actuators['track_to']
ai = [obj for obj in scene.objects if 'track_to' in obj]
if ai:
closest_ai = sorted(ai, key=lambda enemy: own.getDistanceTo(enemy))[0]
distance = own.getDistanceTo(closest_ai)
max_distance = own['track_distance']
if distance <= max_distance:
track_to.object = closest_ai
cont.activate(track_to)
else:
cont.deactivate(track_to)