Whats wrong with this script

 
import math
objectlist = GameLogic.getCurrentScene().getObjectList()
p1 = GameLogic.getCurrentScene().getObjectList()["OBp1"]
enemies = []
distance = []
for object in objectlist:
 if hasattr(object, "bg"):
  enemies.append(object)
  
print enemies
for object in enemies:
 x = object.getPosition()[0]
 y = object.getPosition()[1]
 p1x = p1.getPosition()[0]
 p1y = p1.getPosition()[1]
 dist = math.sqrt(math.pow(x,2) + math.pow(y,2))
 distance.append(dist)
 
print distance
close = min(distance)
print close
idx = distance.index(close)
closob = enemies[idx]
print closob
pi = 3.141592653589793238462
controller = GameLogic.getCurrentController()
p2 = controller.getOwner()
print p2
p1 = closob
p1x = p1.getPosition()[0]
p1y = p1.getPosition()[1]
p1z = p1.getPosition()[2]
pex = p2.getPosition()[0]
pey = p2.getPosition()[1]
pez = p2.getPosition()[2]
xdist = (p1x - pex)
ydist = (p1y - pey)

p1ang = [0.0, 0.0, (((math.atan((ydist/xdist)))))]
p1rot= [0.0, 0.0, (pi+((math.atan((ydist/xdist)))))]
print p1ang
if xdist > 0:
 p2.setOrientation(p1ang)
if xdist < 0:
 p2.setOrientation(p1rot)
del enemies
del distance
print "lists should be empty"
enemies = []
distance = []
print enemies
print distance


This code was to aim at the closest object with the proporty bg. by aim i mean to set its rotation facing towards it. The issue is the objects distance dossent seem to update. so it works the first time, but even if the first object is no longer the closest and you re run the script it still thinks that it is the closest. but if you move the objects before you start the game it will work, but during the game it does not update the distance. any suggestion are helpfull. Please help.

Hi Kylona,

I tested your code in a test scene and it seems to work correctly. I fired the script using an always sensor (with delay of 60) and when I moved the objects around the p1 object, the detection worked correctly. I didn’t see the p1 object rotating towards the detected object, though.

On a side note, I think your bug is in the calculation of distances: given two vectors v1 and v2, used to describe the position of two objects in space, the distance between them is the distance of v1 - v2, which should translate to sqrt((v1x - v2x)^2 + (v1y - v2y)^2), and you are just doing sqrt(v1x^2 + v1y^2).

oh ya… duh… meybe i should go take geomatry again. I feel stupid. Thanks jedihe