【问题标题】:How to move 3D object by pixels in opengl如何在opengl中按像素移动3D对象
【发布时间】:2021-10-03 04:34:47
【问题描述】:

我在前面有一个 3d 模型,在背景中有一个图像。我正在尝试按像素移动 3d 模型 (x, y)。但是 glTranslatef 函数将它移到其他一些指标中。
我尝试 glViewport(0, 0, width, height) 然后 glOrtho(x, width, height, y, 0.0, 1.0) 但它使对象 消失。
这是我的代码:

# draw the 3d model

        glViewport(0, 0, width, height)
        
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        glOrtho(0.0, width, height, 0.0, 0.0, 1.0)

        gluPerspective(45, (width / height), 0.1, 50.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslatef(0, 0, -5)

        glEnable(GL_DEPTH_TEST)
        # reddering the 3d object
        box.render()

【问题讨论】:

  • 你为什么使用 glOrtho gluPerspective?
  • 我没有使用 glOrtho 试图让 3d 消失。如果我删除 gluPerspective 3d 永远不会出现
  • 我是 opengl 的新手,我想我现在可以做什么 gluPerspective 了。
  • 你知道越远的东西越小,所以物体越远你的运动也越小?
  • 是的。但我想按像素移动它。我想知道glTranslatef (x,,y) 值和像素值之间的关系

标签: python opengl pygame pyopengl


【解决方案1】:

此答案扩展了@user253751 在上述问题中的最后一条评论:

是的,您将需要三个矩阵 Model, View and Projection 将您的对象从本地空间转换为 screen coordinates(像素空间)。

OpenGL 转换一般是这样发生的:

World space //Model Matrix --> View Space //View Matrix --> NDC Coordinates (Clip Space) //Projection Matrix --> Screen Coordinates //OpenGL 自动执行此操作

所以要从屏幕坐标(像素坐标)出发,您只需应用这些矩阵的逆矩阵。

例如,您在屏幕坐标中拥有和对象(100, 100),并且您想将其移动到(300, 300)

通过逆视图和投影将坐标(300, 300) 还原为3D 世界空间,找到世界空间坐标(x,y,z),并在那里变换您的对象位置。 (这也称为光线投射

如果没有 MVP 系统设置,您将很难通过像素移动对象。

这是 OpenGL 中 spacecoordinates 上的 good tutorial by LearnOpenGL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多