设置glutBitmapCharacter()的颜色?

时间:2019-02-24 11:36:51

标签: c++ opengl colors glut

我正在尝试增强MoonLander游戏程序-只是试图更好地理解事物。

我想在燃油下降到一定水平以下时添加警告,我希望该警告可以改变颜色。我的游戏循环以每秒30帧的速度运行。因此,我创建了一个成员变量,该变量在特定帧数处“设置” INT。我已经做了一些检查-我的帧计数器代码工作正常-我的setWhichColour函数也是如此。文本确实在屏幕上绘制-但每次都会以白色绘制...

这是设置“ colour”成员变量的代码

   if (lander.getFuel() < 200)
   {
       incrementFrameCounter();
       if (frameCounter % 15 == 0)
       {
           setWhichColour(0);
       }
       else if (frameCounter % 20 == 0)
       {
           setWhichColour(1);
       }
       else if (frameCounter % 50 == 0)
       {
           setWhichColour(2);
       }
       else 
       {}
       drawText(Point(40, 40), "Warning: Fuel Below 200",getWhichColour());
   }

这是我用来在屏幕上绘制文本的drawText函数。仅向case语句传递一个整数值,以选择要触发的glColor3f序列。每次游戏循环运行一次,drawText函数就会运行一次。

void drawText(const Point & topLeft, const char * text, int iColour)
{

    void *pFont = GLUT_BITMAP_HELVETICA_12;  

    // prepare to draw the text from the top-left corner
    glRasterPos2f(topLeft.getX(), topLeft.getY());

    glPushAttrib(GL_CURRENT_BIT); // <-- added this after finding another answer
    switch (iColour)
    {
    case 0: // red
        glColor3f(1.0 /* red % */, 0.0 /* green % */, 0.0 /* blue % */);
    case 1: // green
        glColor3f(0.0 /* red % */, 1.0 /* green % */, 0.0 /* blue % */);
    case 2: //blue
        glColor3f(0.0 /* red % */, 0.0 /* green % */, 1.0 /* blue % */);
    default: //white
        glColor3f(1.0 /* red % */, 1.0 /* green % */, 1.0 /* blue % */);
    }

    // loop through the text
    for (const char *p = text; *p; p++)
        glutBitmapCharacter(pFont, *p);
    glPopAttrib(); // <-- added this after finding another answer
}

我发现这个答案似乎很相关: How to Set text color in OpenGl

我在上面指出了我从那个答案中复制代码的地方,这似乎应该有所帮助。

很遗憾-我的文字仍然是白色的。它根本不设置颜色。我怀疑我缺少一些基本的东西(可能很简单),但是我只是看不到什么。

任何人都可以确定我应该怎么做才能使文本以不同的颜色显示-坦白地说-我什至会满意,即使它没有显示白色也可以显示为其他颜色改变...

这是正在运行的游戏的屏幕截图: GameScreenShot

2 个答案:

答案 0 :(得分:2)

设置颜色后调用glRasterPos

答案 1 :(得分:1)

最后,这是上述datenwolf答案的结合,并且将代码更改为不使用成功的case语句。 (以及来自另一个堆栈答案的其他提示)

我想我应该发布一个答案,以给出最终使它起作用的确切代码...

void drawText(const Point & topLeft, const char * text, int iColour)
{

    void *pFont = GLUT_BITMAP_HELVETICA_12;  // also try _18

    glPushAttrib(GL_CURRENT_BIT);

    if (iColour == 0)
        glColor3f(1.0 /* red % */, 0.0 /* green % */, 0.0 /* blue % */); //red
    else if (iColour == 1)
        glColor3f(0.0 /* red % */, 1.0 /* green % */, 0.0 /* blue % */); //green
    else if (iColour == 2)
        glColor3f(0.0 /* red % */, 0.0 /* green % */, 1.0 /* blue % */); //blue

    // prepare to draw the text from the top-left corner
    glRasterPos2f(topLeft.getX(), topLeft.getY());

    // loop through the text
    for (const char *p = text; *p; p++)
        glutBitmapCharacter(pFont, *p);

    // This line was located in a stackechange answer on how to get colour set
    glPopAttrib();

}