Search code examples
matrix3dgeometrycomputational-geometrysharpdx

Projecting a 3D point to a 2D screen position issue


I have tried 4 methods, all which didn't work. Everywhere else my code works, the camera moves properly and the objects move properly.

I am using SharpDX and my projection matrix is a perspective projection matrix.

I am trying to get the screen position of a 3d point in order to position the cursor at that point.

These are the 4 methods I have tried:

public Vector2 WorldPosToScreenPos1(Vector3 p)
{
    Vector3.Transform(ref p, ref View, out p);
    Vector3.Transform(ref p, ref Projection, out p);

    return new Vector2(
        RenderForm.ClientSize.Width * (p.X + 1) / 2,
        RenderForm.ClientSize.Height * (1 - (p.Y + 1) / 2)
        );
}

public Vector2 WorldPosToScreenPos2(Vector3 p)
{
    Vector3.Transform(ref p, ref View, out p);
    Vector3.Transform(ref p, ref Projection, out p);
    p.X /= p.Z;
    p.Y /= p.Z;
    p.X = (p.X + 1) * RenderForm.ClientSize.Width / 2;
    p.Y = (p.Y + 1) * RenderForm.ClientSize.Height / 2;

    return new Vector2(p.X, p.Y);
}

public Vector2 WorldPosToScreenPos3(Vector3 p)
{
    Viewport viewport = new Viewport(0, 0, RenderForm.ClientSize.Width, RenderForm.ClientSize.Height);
    viewport.Project(ref p, ref ViewProj, out p);

    return new Vector2(p.X, p.Y);
}

public Vector2 WorldPosToScreenPos4(Vector3 p)
{
    Vector3.Project(p, 0, 0, RenderForm.ClientSize.Width, RenderForm.ClientSize.Height, 1, 10000, ViewProj);
    return new Vector2(p.X, p.Y);
}

In all four methods (which all give different results) the 2d position I get is off, often by a big margin. What am I doing wrong?


Solution

  • It turns out the 4th method was right, all it had missing was retrieving the value returned by Vector3.Project().

    The 3 other methods still gave significantly different results and I still don't know why they didn't work. If someone knows, I'd appreciate to know.