Getting position relative to another object

I need to get the position of an object in relativity to my camera, as if the camera was the center of my world. I’ve been searching around, but I haven’t found anything to help me get position relative to other objects. Is it possible? Thanks for the help!

You’d have something like this script run as part of the logic setup for the objects.


import GameLogic
con = GameLogic.getCurrentController()
obj = con.owner

scene = GameLogic.getCurrentScene()
list = scene.objects
camera = list['Camera']

objPos = obj.worldPosition.copy()
camPos = Camera = worldPosition.copy()

if objPos[0] < 0:
    objPos[0] *= -1
elif objPos[1] < 0:
    objPos[1] *= -1
elif objPos[2] < 0:
    objPos[2] *= -1

if camPos[0] < 0:
    camPos[0] *= -1
elif camPos[1] < 0:
    camPos[1] *= -1
elif camPos[2] < 0:
    camPos[2] *= -1

relativePosition = (objPos[0]-camPos[0], objPos[1]-camPos[1], objPos[2]-camPos[2])

This is assuming you want the distance as a set of coordinates as your question implies, if you want the literal distance, you can just use getDistanceTo(camera)

To find a vector relative to another vector, you take the difference of the two vectors. In this case your two vectors are positions, lets say vector A and vector B. To get the position of B relative to A, you simply take the difference (B-A).

Or in terms of python:
rel_position = camera.worldPosition - obj.worldPosition

object.getVectTo(other) returns the vector and the straight line distance to another object or point. (other) is the name of the other object OR it’s world location tuple. If the object making the call is not at the world origin, TWO location vectors are returned as well as the scalar distance between the objects or the calling object and the point.

It’s a really nifty function.

Wow, thanks for all the replys, that getVectorTo is a really neat function, I think I’ll be using that a lot. These forums have really helped with learning python, thanks again.