屏幕2D指向3D世界

时间:2019-10-24 11:44:34

标签: 3d 2d point

我应该将屏幕上的点的坐标转换为3D场景中的3D坐标。 我已经看到了几种解决方案,但我不是这些方面的专家,并且我有一个可用的SDK,其中各个用户建议的步骤并不多。 我所能提供的是: 2D点的XY坐标 相机视图的矩阵 相机投影的矩阵

这就是我想要做的:

Public Shared Function UnProject(ByRef projection As Matrix4x4, view As Matrix4x4, viewport As Size, mouse As Vector2, Optional zIN As Single = 0) As Vector4
    Dim vec As Vector4
    'https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluUnProject.xml
    'https://gamedev.stackexchange.com/questions/51820/how-can-i-convert-screen-coordinatess-to-world-coordinates-in-opentk
    vec.X = ((2.0F * mouse.X) / CSng(viewport.Width)) - 1
    vec.Y = -(2.0F * mouse.Y / CSng(viewport.Height) - 1)
    vec.Z = zIN
    vec.W = 1.0F

    Dim viewInv As Matrix4x4

    Matrix4x4.Invert(view, viewInv)
    Dim projInv As Matrix4x4
    Matrix4x4.Invert(projection, projInv)


    vec = Vector4.Transform(vec, projInv)
    vec = Vector4.Transform(vec, viewInv)

    If vec.W > Single.Epsilon OrElse vec.W < Single.Epsilon Then
        vec.X /= vec.W
        vec.Y /= vec.W
        vec.Z /= vec.W
    End If

    Return vec
End Function

我有一个Panel,外部库通过panel.handle绘制OpenGL场景。 在mouseUp事件中,我得到了CameraView和CameraProject矩阵 获取视口大小(面板为,面板高度为),然后调用unproject作为起点和终点(我想进行矩形选择)

Dim vp As New Size(Me.Width, Me.Height)
Dim vm As New Vector2(ox, oy)
Dim v4 As Vector4 = UnProject(m4Proj, m4View, vp, vm, 0)
Dim vm2 As New Vector2(e.X, e.Y)
Dim v42 As Vector4 = UnProject(m4Proj, m4View, vp, vm2, 0)

但是X,Y,Z不太准确... 另一个问题 ? Z:应该在-1和1之间?还是0和1?

0 个答案:

没有答案