c - glutSolidSphere 和 GL_LINE_STRIP 在不同位置绘制但基于相同位置

标签 c opengl

我正在创建一个行星模拟,其中有 glutSolidSpheres 围绕太阳运行并且应该有跟踪线跟随它,使用 GL_LINE_STRIP 创建。

我遇到的问题是,这条轨迹并没有直接跟随行星在它后面,它看起来好像在显示行星与太阳的距离,但在另一边。请查看下图了解我的意思。

enter image description here

行星存储在双向链表中,每个链表都包含一个链表来存储路径的位置。每次更新行星位置时,都会将该位置添加到轨迹中。

用于绘制轨迹线的代码如下所示:

for (struct planet *planet = head; planet != 0; planet = planet->next) {
        glPushMatrix();
        glTranslatef(planet->position[0], planet->position[1], planet->position[2]);//X, Y, Z
        glutSolidSphere(planet->mass, 10, 10);//Radius, slices, stacks
        if (!planet->isSun) {
            if (planet->trailStarted) {
                glDisable(GL_LIGHTING);
                glBegin(GL_LINE_STRIP);
                glLineWidth(1);
                for (struct trail *trail = planet->trailHead; trail != 0; trail = trail->next)
                {
                    glVertex3f(trail->position[0], trail->position[1], trail->position[2]);
                }
                glEnd();
                glEnable(GL_LIGHTING);
            }
        }
        glPopMatrix();
    }
    glFlush();
    glutSwapBuffers();
}

这些位置确实按照它们应该的方式相互跟随,打印出您在上面看到的 for 循环中的结果给出了这个模拟的以下结果。 P代表行星位置,T代表轨迹位置: enter image description here

如果有人能阐明它为什么这样做,那就太好了。如果您需要任何进一步的信息,请告诉我。

最佳答案

已经有来自以下行的有效翻译:

glTranslatef(planet->position[0], planet->position[1], planet->position[2]);

也就是说坐标系的原点在行星。所以在绘制的时候,要么需要减去行星坐标:

for (struct trail *trail = planet->trailHead; trail != 0; trail = trail->next)
{
    glVertex3f(trail->position[0] - planet->position[0], trail->position[1] - planet->position[1], trail->position[2] - planet->position[2]);
}

或者您需要在绘制轨迹之前执行 glPopMatrix()。 我更喜欢第二个选项:

for (struct planet *planet = head; planet != 0; planet = planet->next) {
    glPushMatrix();
    glTranslatef(planet->position[0], planet->position[1], planet->position[2]);//X, Y, Z
    glutSolidSphere(planet->mass, 10, 10);//Radius, slices, stacks
    glPopMatrix();
    if (!planet->isSun) {
        if (planet->trailStarted) {
            glDisable(GL_LIGHTING);
            glBegin(GL_LINE_STRIP);
            glLineWidth(1);
            for (struct trail *trail = planet->trailHead; trail != 0; trail = trail->next)
            {
                glVertex3f(trail->position[0], trail->position[1], trail->position[2]);
            }
            glEnd();
            glEnable(GL_LIGHTING);
        }
    }
}
glFlush();
glutSwapBuffers();

关于c - glutSolidSphere 和 GL_LINE_STRIP 在不同位置绘制但基于相同位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526948/

相关文章:

c++ - 如何将可变参数参数传递给另一个函数?

c - 静态常量

c++ - 使聚光灯静止

opengl - 旋转后向右、向上和向前不正确

c - C中的系统调用功能

C - scanf 没有因用户输入而停止

c - 在 C 中将负数传递给 "%hu"

opengl - X11 全屏窗口 (OpenGL)

OpenGL 帧缓冲区 : can clear it, 但无法绘制到它

c++ - Opengl 相机和乘法矩阵