Issues with animation - translation, projection OpenGL/C++

混江龙づ霸主 提交于 2021-01-28 05:34:18

问题


Recently I had this issue. Now that I've fixed that with given solution, I ran into some other issues. Here is a gif of the animation I have to achieve.

Issues I have now are: the ball in my animation doesn't look like it's moving forwards and backwards like it is at the beginning of the .gif. I do believe this has something to do with Ortho but I don't know how to fix this.

Also, at some point, when it's moving completely to the right, the moving ball and torus just get "swallowed", it's visible only at the starting point and slowly disappears when translating along z-axis. Here is the code I have.

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glPushMatrix();
    glColor3f(0.26f, 0.74f, 0.73f);
    glutWireTorus(0.2, 0.85, 17, 30);

    glPushMatrix();
    glTranslatef(0.0, 0.0, tra);
    glColor3f(0.9f, 0.5f, 0.3f);
    glutWireSphere(0.5, 17, 15);

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(ex+0.0, ey+0.0, ez+10.0, cx, cy, cz, 0.0, 1.0, 0.0);
    glFlush();
    }

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    float sx = w / 70.0f;
    float sy = h / 70.0f;
    glOrtho(-sx/2.0f, sx/2.0f, -sy/2.0f, sy/2.0f, 1.0f, 600.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

I believe there are some mistakes inside this part.


回答1:


If you want a perspective projection, where the size of the objects is relative to screen resolution and independent on the the size of the window, then you have to compute the filed of view angle in relation to the height of the window:

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float angle_rad = atan((float)h / 600.0f) * 2.0f;
    float angle_deg = angle_rad * 180.0f / M_PI;
    gluPerspective(angle_deg, (GLfloat)w / (GLfloat)h, 1.0, 80.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

The relation between the field of view angle and the size of an object is tan(fov / 2) * 2., thus the fov = atan(size) * 2, where size depends on the size of the window ((float)h / 600.0f).
You have to adjust the divider (600.0f) for your needs.



来源:https://stackoverflow.com/questions/61816720/issues-with-animation-translation-projection-opengl-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!