
Untitled
By: a guest on May 13th, 2009 | syntax:
C# | size: 1.09 KB | hits: 93 | expires: Never
/// <summary>
/// Project a 3D point given it's world coordinates and the viewing <see cref="Camera"/> to 2D screen space.
/// </summary>
/// <remarks>
/// The screen space is assumed to be in range [0..1] in both x and y dimensions, where 0 means the left/top and 1 the right/bottom edge.
/// </remarks>
/// <param name="camera">The viewing camera</param>
/// <param name="position">World position of the point to be projected</param>
/// <returns></returns>
public static Vector2 GetScreenCoords(Camera camera, Vector3 position)
{
// projection calculation
Vector4 v4
= new Vector4
(position.
x, position.
y, position.
z, 1.0f
);
Vector4 pos = camera.ProjectionMatrix * camera.ViewMatrix * v4;
Vector2 screenPos
= new Vector2
(pos.
x / pos.
w,
-pos.
y / pos.
w);
// normalize screen position
screenPos.x = (screenPos.x + 1.0f) * 0.5f;
screenPos.y = (screenPos.y + 1.0f) * 0.5f;
return screenPos;
}