将 3D 点投影到 2D 屏幕位置问题 [英] Projecting a 3D point to a 2D screen position issue

查看:48
本文介绍了将 3D 点投影到 2D 屏幕位置问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了 4 种方法,都没有奏效.我的代码在其他任何地方都能正常工作,相机可以正常移动,对象也可以正常移动.

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

我使用的是 SharpDX,我的投影矩阵是透视投影矩阵.

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

我正在尝试获取 3d 点的屏幕位置,以便将光标定位在该点.

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

这是我尝试过的 4 种方法:

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);
}

在所有四种方法(都给出不同的结果)中,我得到的 2d 位置经常偏离很大.我做错了什么?

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?

推荐答案

结果证明第 4 种方法是正确的,它所缺少的只是检索 Vector3.Project() 返回的值.

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

其他 3 种方法仍然给出了显着不同的结果,我仍然不知道为什么它们不起作用.如果有人知道,我很高兴知道.

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.

这篇关于将 3D 点投影到 2D 屏幕位置问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆