I have these two scrips (they ain’t mine) that let a object track to the nearest object with that property:
import GameLogic as g
cont = g.getCurrentController()
own = cont.getOwner()
scene = g.getCurrentScene()
objList = scene.getObjectList()
#create a list of all enemies within range 100 #change this number to best fit your game area
g.enemyList=
for i in range(0,len(objList)):
obj = objList[i]
if hasattr(obj,“trackto”):
if own.getDistanceTo(obj) <100:
g.enemyList.append((obj.name))
import GameLogic as g
cont = g.getCurrentController()
own = cont.getOwner()
objList = g.getCurrentScene().getObjectList()
#check to see if there are any enemies within range
if len(g.enemyList) > 0: #create a list of the enemies within range and their distances #each list item has 2 parts: (distance, OBname)
enemyRanges =
for i in range(0,len(g.enemyList)):
enemy = objList[g.enemyList[i]]
dist = own.getDistanceTo(enemy)
enemyRanges.append((dist,enemy.name)) #sort the list #the first object will be the one with the shortest distance
enemyRanges.sort() #get the second item (OBname) of the first list item #then strips ‘OB’ from the string
nearestEnemy = enemyRanges[0][1][2:] #set the trackTo actuator
track.setObject(nearestEnemy) #activate the actuators
g.addActiveActuator(track,1)
g.addActiveActuator(motion,1)
own.shoot = True
else: #if there are no enemies, activate only the motion actuator
g.addActiveActuator(track,0)
g.addActiveActuator(motion,1)
own.shoot = False
Anyone know why it won’t work with objects that are added to the game with an empty?
Try the S2A.closestHitObjectToObject. This is much more flexible. It provides the full power of radar and near sensors, while there is no need to change the code.
Check out the doc for the description. Have a look for the demo file to see how to setup.
Hey,
Sorry for the late reply but how does this work?? There are way to many different things in your file and all I want is a simple object track to the closest added object.
Finding the nearest object can be tackled quite easily using the sorted function:
target_object = ... # object to do the tracking
object_list = [...] # use current_scene.objects or manually build it based on properties ect
nearest_object = soredt(object_list, key=lambda obj: obj.getDistanceTo(target_object))[0] # sort the list and take the first element