# Proyecting 3D point to camera (2D)

luismesas

20-08-2009 10:35:10

I have ported the Ogre wiki page with snippet to convert 3D points to 2D point proyected to camera.

http://www.ogre3d.org/wiki/index.php/MOGRE_Projecting_3D_position_to_2D

// using MOGRE;
// returns a vector with x,y with clamped screencoords in [-1;1]

public Vector2 ProjectPos (Camera cam, Vector3 pos)
{
Vector2 ret = new Vector2();

Vector3 eyeSpacePos = cam.GetViewMatrix(true) * pos;
if (eyeSpacePos.z < 0)
{
Vector3 screenSpacePos = cam.ProjectionMatrix * eyeSpacePos;
ret.x = screenSpacePos.x;
ret.y = screenSpacePos.y;
}
else
{
ret.x = (-eyeSpacePos.x > 0) ? -1 : 1;
ret.y = (-eyeSpacePos.y > 0) ? -1 : 1;
}

return ret;
}

dannypb

16-07-2011 22:55:07

Using Mogre 1.7

I used exactly this function and I am getting very strange results. I pass the camera object and the scene node position for the object I want to overlay. I am wondering though, since i don't fully understand what the function is doing yet, is the fact that my camera object is a child of a scene node possibly causing issues? The camera's position stays at 0,0,0 because of this, but I dont see it effecting the view matrix. The x and y values it remain at -1 and -1 when I'm looking right at the target. the eyeSpacePos.z is at -7687.49, I amm looking at it on the positive x side, the target has a higher x position value and I', looking close to down the x axis at the target.

I'll keep playing with it in the meantime.

dannypb

18-07-2011 03:34:58

FYI, I have it working, I'll post the changes I made to make it work for me, when I'm not so exausted. I'm prolly using it wrong, but it still works

Beauty

29-07-2011 22:57:47

Thanks for this useful code snippet and also for creating a related wiki page

Improvements by dannypb (or others) are welcome.
Please don't just the changes here, update the code in the wiki, too.