Monday 4 March 2013

XNA 4.0 Tutorial: Converting Screen Position To World Position Function

/// <summary>
/// Convert screen position to world position
/// </summary>
public Vector3 ScreenToWorld(Vector2 inPos)
{
    Vector3 minPointSource = graphics.GraphicsDevice.Viewport.Unproject(new Vector3(inPos, 0f), camera.GetProjectionMatrix(), camera.GetViewMatrix(), Matrix.Identity);
    Vector3 maxPointSource = graphics.GraphicsDevice.Viewport.Unproject(new Vector3(inPos, 1f), camera.GetProjectionMatrix(), camera.GetViewMatrix(), Matrix.Identity);

    Vector3 dir = maxPointSource - minPointSource;
    float zFactor = -minPointSource.Y / dir.Y;
    Vector3 zeroWorldPoint = minPointSource + dir * zFactor;

    return zeroWorldPoint;
}

No comments:

Post a Comment