your nearest object

Anyone know how, using python i can get the nearest object to you and then move to its location.

The moving to an objects location should be easy with.

pos = nearest.worldPosition
player.worldPosition = [pos[0],pos[1] , pos[2]]

Or Similar
And i have attached a blend which locates the nearest.

But instead of tracking the nearest i want to move the player to the location of nearest.

I have not figured out how to get the nearest object to work in code above.

In this file i want to be able to load the .worldPosition and possibly the .worldOriantation of the “closest” object.

Attachments

track to closest rev1 .blend (152 KB)

But instead of tracking the nearest i want to move the player to the location of nearest.
If you can track, that means your object’s axis is already aligned to the good vector.
You just need to apply movement (or impulse, or setlinearvelocity) to your character.

  1. Change your Cube to Dynamic (instead of static)
  2. I added this under the trackToClosest(cont), and it works :

yspeed=5
own.setLinearVelocity([0.0, yspeed, 0.0],1)

Isn’t it what you were trying to get?

That works well.

but i would also like to be able to know what the world position and world oriantation of the closest object is. This is so i can snap the player onto the nearest.

Does “closest” not contain this info?

Don’t have much time to check but I did a little test (attached file).

Isn’t your object already tracking the nearest.

Attachments

track to closest rev1 .blend (139 KB)

I don’t want it to track to the nearest. I want it to move to the exact position and orientation ot the nearest object.

This is why i want to access the .worldPosition and .worldorientation of the closest object.

Documentation
WorldPosition
WorldOrientation
Updated to 2.49…

cont = GameLogic.getCurrentController() 
own = cont.owner 
 
scn = GameLogic.getCurrentScene() 
ob = scn.objects 
track_ob = cont.actuators["track"] 
move_ob = cont.actuators["moveaway"] 
 
     
def trackToClosest(cont): 
    own = cont.owner 
    prop = 'cube' 
    obl = [ob for ob in scn.objects if ob.has_key(prop)] 
     
    closest = [obl[0], own.getDistanceTo(obl[0])] 
 
    for ob in obl[1:]: 
        dis = own.getDistanceTo(ob) 
        if  dis < closest[1]: 
            closest = [ob, dis] 
    #print closest 
    pos=closest[0].worldPosition 
    print "World position: ", pos 
    orient = closest[0].worldOrientation 
    print "World orientation ", orient 
    track_ob.object =closest[0] 
    cont.activate(track_ob) 
     

trackToClosest(cont) 
own.setLinearVelocity([0,3,0],1)

You have your variables pos and orient.
Do whatever you want with it.

Great work.

I’ll see if i can do what im after.

Cheers.