c++ - 将 2D 对象移动到 OpenGL 中的一个点

标签 c++ c opengl

如何使用 OpenGL 沿点(不是 GL_POINTS,而是坐标)的方向移动二维对象?

为了更好地理解我的代码:

我已将我的大部分代码拆分为不同的源代码,但这是实际创建形状和设置场景的源代码:

void setupScene(int clearColor[]) {
    glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
    //glClearColor(250, 250, 250, 1.0);  //  Set the cleared screen colour to black.
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);  // This sets up the viewport so that the coordinates (0, 0) are at the top left of the window.
    
    // Set up the orthographic projection so that coordinates (0, 0) are in the top left.
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, -10, 10);
    
    // Back to the modelview so we can draw stuff.
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen and depth buffer.
}

void drawScene() {
    setupScene((int[]){250, 250, 250, 1});
    
    triangle(210, WINDOW_WIDTH, WINDOW_HEIGHT);
    
    glBegin(GL_QUADS);
    glColor3f(RGB(80), RGB(80), RGB(80));

    glPushMatrix();
    glTranslatef(400, 400, 0);
    glVertex2d(200, 100);
    glVertex2d(100, 100);
    glVertex2d(100, 200);
    glVertex2d(200, 200);
    glPopMatrix();
    glEnd();
    
    glutSwapBuffers();  // Send the scene to the screen.
}

void update(int value) {
    glutPostRedisplay();  // Tell GLUT that the display has changed.
    glutTimerFunc(25, update, 0);  // Tell GLUT to call update again in 25 milliseconds.
}

最佳答案

您需要翻译模型 View 矩阵。假设您已经处于模型 View 模式:

glPushMatrix();
glTranslatef(x, y, z);
// Draw your shape
glPopMatrix();

[编辑]

@paddy: Something like this? I tried this but the square isn't moving. pastebin.com/2PCsy5kC

尝试明确选择模型 View 矩阵。您的示例没有告诉我们它当前处于哪种模式:

glSetMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x, y, z);
// Draw your shape
glPopMatrix();

通常在渲染开始时,您会重置所有内容...所以您进入 GL_PROJECTION 模式,调用 glLoadIdentity() 重置它并设置您的相机,然后为 GL_MODELVIEW 矩阵执行此操作

关于c++ - 将 2D 对象移动到 OpenGL 中的一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11731268/

相关文章:

c - C 中的按位操作

C++ Raytracer 与 opengl 在特定分辨率下显示倾斜

c++ - 如何在 C++ 中为 GLSL 片段着色器实现 iGlobalTime?

c++ - 静态初始化器在库中时被优化掉

c++ - 从 Visual Studio 启动应用程序时出现页面错误

c++ - 流填充字符的默认定位

c++ - GTK+ 3、C、C++ - 使用库存图片创建按钮

c - 如何优雅地异步停止 X11 事件循环

c - C 中的循环 ID 生成器

Opengl:根据 Z 的值,将四边形拟合到屏幕上