我试图在OpenGL的画布上打印一行包含变量和点的文本。我的代码如下:
void display()
{
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
char string[50];
sprintf(string, "Base Rotation: %d", numVertices);
renderMyText(-0.4, 0.35, string);
glPointSize(20);
glBegin(GL_POINTS);
glVertex2f(characterX, characterY);
dx = vertices[numVertices-1].x-ox;
dy = vertices[numVertices-1].y-oy;
dt = glutGet(GLUT_ELAPSED_TIME);
characterX = ox + dx / sqrt(dx*dx+dy*dy) * Velocity * dt;
characterY = oy + dy / sqrt(dx*dx+dy*dy) * Velocity * dt;
printf("%f %f", characterX, characterY);
glEnd();
glFlush();
}
我使用不同的方法在鼠标移动时更新点位置。该代码一切正常,方块更新了它的位置并完美移动,直到我添加了文本行。
现在发生的事情是,一旦我启动程序,方形和文本出现,但是一旦我在窗口中移动鼠标,方块消失,只有文本保留,我希望它们中的两个留在窗口中。谁能看到什么错了?
答案 0 :(得分:1)
我解决了这个问题所以我觉得我应该添加解决方案:
我是以不正确的方式解决这个问题,我应该在空闲方法中更新我的坐标值,如下所示:
void idle()
{
//dx is last mouse x - last box x
dx = vertices[numVertices-1].x-ox;
//dy is last mouse y - last box y
dy = vertices[numVertices-1].y-oy;
dt = 50;
//dt helps to control the chasing charcters speed
characterX = ox + dx / sqrt(dx*dx+dy*dy) * Velocity * dt;
characterY = oy + dy / sqrt(dx*dx+dy*dy) * Velocity * dt;
//equations to move the character after the cursor by moving it along the slope of the line between the two points
ox = characterX;
oy = characterY;
//update object x and y for next calculation
if((numVertices > 5) && characterX >= vertices[numVertices-1].x - 1 && characterX <= vertices[numVertices-1].x + 1 && characterY >= vertices[numVertices-1].y -1 && characterY <= vertices[numVertices-1].y + 1) {
endGame = true;
//vertices over 5, so that we don't accidentially die when we start, this collision detection code works on a threshold of contact of one
//between the cursor and object on the X and Y
}
glutPostRedisplay();
}
然后glutPostRedisplay调用display方法,我在这里使用坐标计算来改变屏幕上Point的位置:
void display() {
glColor3f(0,255,0); //set the in game text to green
if(endGame == true) {
glColor3f(255,0,0);
//if the game is over set the text to red
}
glClear (GL_COLOR_BUFFER_BIT);
glPointSize(20);
glBegin(GL_POINTS);
glVertex2f(characterX, characterY);
glEnd();
glFlush();
glutSwapBuffers();
}