Projecting a 3D point onto a 2D position on the screen

I tried 4 methods, all that didn't work. Wherever my code is running, the camera moves correctly and the objects move as expected.

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 to place the cursor at that point.

These are the 4 methods I 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 give different results) the 2nd position I get is disabled, often by a wide margin. What am I doing wrong?

0


source to share


1 answer


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



The other 3 methods still gave significantly different results and I still don't know why they don't work. If anyone knows, I would appreciate it.

0


source







All Articles