c - 在窗口 OpenGL 中一起打印变量和多边形

标签 c opengl

我正在尝试在 OpenGL 的 Canvas 上打印一行包含一个变量和一个点的文本。我的代码如下:

 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();
}

我正在使用一种不同的方法来在鼠标移动时更新点的位置。该代码一切正常,正方形更新了它的位置并完美移动,直到我添加了文本行。

现在发生的情况是,一旦我启动程序,方 block 和文本就会出现,但是一旦我在窗口中移动鼠标,方 block 就会消失,只剩下文本,我希望它们两个留在窗口中。谁能看出哪里出了问题?

最佳答案

我解决了这个问题,所以我觉得我应该添加解决方案:

我以错误的方式解决了这个问题,我应该像这样在空闲方法中更新我的坐标值:

    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 调用显示方法,我在这里使用坐标计算来更改点在屏幕上的位置:

        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();
}

关于c - 在窗口 OpenGL 中一起打印变量和多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326913/

相关文章:

php - 来自 openssl lib 的 c MD5 与 php md5 不匹配怎么来的?

c++ - 如何检查我的程序是否有数据通过管道传输到其中

c++ - Hook OutputDebugStringA 引发异常

opengl - 在 Arrow 内调用 IO Monad

c - 初始化指向动态内存的全局指针时出错

c++ - 在派生构造函数中生成参数时,如何将参数传递给默认构造函数?

c++ - 如何将 FBO 的文本附件绘制到默认帧缓冲区?

opengl - 如何指定内部格式为 RGBA2 的纹理图像?

opengl - 从 GLSL 版本 1.20 开始允许 GLSL Uniforms 初始化

将字符转换为整数的正确方法