World position to camera space for GUI-working but problems

Hey there!

I am currently working on the interface for my game and for that I wrote a script that is supposed to convert the world position of a target object to the the GUI space position of a representative GUI object.

According to my reflections, this should work by getting the local position of the game object relative to the camera, which I will then use to get the x and y axis rotation difference to the -Z axis of the camera.
Those values will afterwards be divided by half of the radian value of the fov of the game scene cam.
This gives me the x, y values, both ranges from -0.5 to 0.5, left screen edge to right screen edge and from top to bottom.

As the GUI cam has an orthographic scale of 1.0, I can directly set the position of the representative GUI object to the GUI cam position (without z axis) + the x and y value.

But it is not working as it’s expected to:
When I have a small fov only on the game cam, it will work pretty exactly and everything will be on the right place, but the bigger the fov value, tho more inaccurate this will be. (For me that looks like with bigger fov the x and y values will be too small.)


def worldToCamera(self, world_position):
        cam = game.active_camera
        position = world_position - cam.worldPosition
        position.rotate(cam.worldOrientation.inverted())
        vector = -tools.getAxisVect(cam, 2)
        rotation = vector.rotation_difference(position).to_euler()
        angle_1, angle_2 = rotation[1], rotation[0]
        position =gui.active_camera.worldPosition.to_2d() + mathutils.Vector((-angle_1, angle_2)) / radians(cam.fov)
        self.worldPosition[0] = position[0]
        self.worldPosition[1] = position[1]

Does anyone know where I made my mistake, because honestly I can’t find it myself…

Thanks!

EDIT: I attached a picture showing the principle this is supposed to work on.

Attachments


I doubt the general correctness of your algorithm, and your picture doesn’t really hash out the rationale behind your code.

You should just use cam.getScreenPosition(worldposition_or_gameobject)

Thanks Goran, now it works perfectly! Maybe I should have checked the camera API documentation before trying to calculate the screen position myself…