我一直在用freeglut(在虚拟机上的Linux上)尝试一些简单的绘图和动画。直到现在,所有建造和工作的东西都被罚款。我最近的尝试是用glTimerFunc
移动一个方块。虽然它与gcc stack.c -lGL -lglut -o stack
没有任何错误而构建,但动画本身不起作用。我看过每一个我能找到的过量动画的例子,但是我的代码没有看到任何问题。谁能向我解释我的错误是什么?
(编辑:见下面的工作代码)
#include <stdio.h>
#include <stdlib.h>
#include <GL/freeglut.h>
int dx = 0;
#define TIMERSECS 100
void animate(int value) {
glutTimerFunc(TIMERSECS, animate, 1);
if (dx > 0.5) {
dx = -0.5;
}
else {
dx += 0.1;
}
glutPostRedisplay();
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.5);
glBegin(GL_POLYGON);
glVertex2d(-0.5+dx, 0.5);
glVertex2d(-0.5+dx, -0.5);
glVertex2d(0.5+dx, -0.5);
glVertex2d(0.5+dx, 0.5);
glEnd();
glutSwapBuffers();
}
void initialize(void) {
glClearColor(1.0, 1.0, 1.0, 1.0);
glShadeModel(GL_SMOOTH);
}
void main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500, 500);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutCreateWindow(argv[0]);
initialize();
glutDisplayFunc(display);
glutTimerFunc(TIMERSECS, animate, 0);
glutPostRedisplay();
glutMainLoop();
}
修改
@datenwolf:我这次看了你更仔细回答的other question并从那里拿了一些代码,效果很好!
这是新版本:
#include <stdio.h>
#include <stdlib.h>
#include <GL/freeglut.h>
int factor=100; // factor the animation is slowed down by
double dx = 0;
void animate(double speed);
static double ftime(void) {
struct timeval t;
gettimeofday(&t, NULL);
return 1.0*t.tv_sec + 1e-6*t.tv_usec;
}
static double last_T;
static void idle(void) {
const double now_T = ftime();
const double delta_T = now_T - last_T;
last_T = now_T;
const double speed = delta_T * 60;
animate(speed);
glutPostRedisplay();
}
void animate(double speed) {
if (dx > 1.5) {
dx = -1.5;
}
else {
dx += speed/factor;
}
glutPostRedisplay();
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 0.5);
glBegin(GL_POLYGON);
glVertex2d(-0.5+dx, 0.5);
glVertex2d(-0.5+dx, -0.5);
glVertex2d(0.5+dx, -0.5);
glVertex2d(0.5+dx, 0.5);
glEnd();
glutSwapBuffers();
}
void initialize(void) {
glClearColor(1.0, 1.0, 1.0, 1.0);
glShadeModel(GL_SMOOTH);
}
void main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500, 500);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutCreateWindow(argv[0]);
initialize();
glutDisplayFunc(display);
glutIdleFunc(idle);
glutPostRedisplay();
glutMainLoop();
}
DankeschönfürdeineHilfe!
答案 0 :(得分:5)
您不应该为动画使用事件计时器。相反,你应该从idle函数调用glutPostDisplay并测量调用display function之间的时间并将动画时间基于此。