【问题标题】:glutMotionFunc ''Flipping" IssueglutMotionFunc“翻转”问题
【发布时间】:2020-04-16 14:48:21
【问题描述】:

我需要一些真正的 OpenGL 故障排除。我正在使用 OpenGL 和 Freeglut

我使用glutMotionFunc();glRotatef(); 的组合进行了适当的场景旋转(有点像 3pp)。

这是我的旋转功能:

float xrot = 0, yrot = 0, zrot = 0, lastx, lasty, lastz;


void mouseMovement(int x, int y)
{
    int diffx = x - lastx; 
    int diffy = y - lasty; 
    lastx = x;
    lasty = y;
    xrot += (float)diffy;
    yrot += (float)diffx;
}

我的显示功能:

void display(void)
{
    glClearColor(0.0, 0.0, 0.0, 1.0);                   
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -cRadius);
    glRotatef(xrot, 1.0, 0.0, 0.0);
    glRotatef(yrot, 0.0, 1.0, 0.0);         
    glBegin(GL_LINES);
    ---------
    ----
    glEnd();
    glTranslated(-xpos, 0.0f, zpos);
    glutSwapBuffers();      
}

最后是主要功能:

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Window");
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMotionFunc(mouseMovement);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return 0;
}

现在,当我加载时,场景渲染得很好,当我用鼠标(LMB)单击并拖动场景时,旋转会顺利进行。

唯一的问题是,在通过拖动旋转场景的过程中,场景在开始旋转之前会翻转到不同的位置。即,当我再次单击并拖动时,场景的旋转不会从我在上一次鼠标拖动事件中离开的位置继续,而是翻转到一些随机的 xrot 和 yrot 位置。

希望我说清楚。如果有人可以尝试复制相同的内容并提供一些关于此处可能存在的问题的见解,那将很有帮助。

这也是我的重塑功能,以防万一这里也缺少任何东西

void reshape(int w, int h)
{
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60, (GLfloat)w / (GLfloat)h, 0.1, 500.0);
    glMatrixMode(GL_MODELVIEW);
}

【问题讨论】:

    标签: c++ opengl glut freeglut opengl-compat


    【解决方案1】:

    问题是由于lastxlasty 未初始化造成的。第一次调用mouseMovement 回调时,它们没有说明先前的缪斯位置,这导致第一次旋转是随机的。
    注意,lastxlasty 的值在设置之前被读取:

    int diffx = x - lastx; 
    int diffy = y - lasty; 
    lastx = x;
    lasty = y;
    

    您可以通过实现glutMouseFunc 回调来解决这个问题。在回调中设置lastxlasty,这样当鼠标按下时变量就会被初始化:

    void mouseFunc(int button, int state, int x, int y) {
        lastx = x;
        lasty = y;
    }
    
    int main(int argc, char **argv) {
        // [...]
    
        glutMouseFunc(mouseFunc);
    
        // [...]
    }
    

    【讨论】:

    • 如果你看到我的void mouseFunc(),它已经被初始化并且它们没有被'0'初始化。lastx lasty 只是被声明为float。
    • 对不起,伙计。我确实试过了。但发生了轻微的混乱。我使用的是glutMotionFunc 而不是你的glutMouseFunc。它现在起作用了。非常感谢!!
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2012-10-26
    • 1970-01-01
    • 2019-05-25
    • 2011-11-21
    • 1970-01-01
    相关资源
    最近更新 更多