【问题标题】:Alternative to global variables - GLUT C全局变量的替代方案 - GLUT C
【发布时间】:2020-02-12 14:48:18
【问题描述】:

我正在用 C(不是 C++)制作 Dino Race 游戏,并且我正在使用 GLUT 来制作图形。我遇到了问题,因为我必须从 Display() 函数和移动它的函数访问“绘图”的 x 位置。我不能使用全局变量,我该怎么办?

【问题讨论】:

  • 位置不是存储在对象中,作为成员吗?
  • 对不起,我不正确地使用了“对象”。我的意思是我有一个“绘图”的 x 坐标,我必须在两个函数之间共享它。
  • 所以创建一个struct,其中包含有关绘图的所有信息。然后你将一个指针传递给你的函数,并将struct 的图像部分传递给渲染机器。
  • 你能举个例子吗?抱歉,我对此很陌生。

标签: c window global-variables glut freeglut


【解决方案1】:

使用 glut 时,除了使用全局变量之外,您真的别无选择。有点烂,但你有它。如果你真的想,你可以将变量打包成一个类,类似这些......

class MyGame
{
public:
  MyGame(int argc, char* argv[])
  {
    assert(g_game);
    glutInit(&argc, argv);

    // do all the usual glutCreateWindow / glutInitDisplayMode stuff here 

    // attach to the static glut_draw method (which will call draw)
    glutDisplayFunc(glut_draw);
    glutMainLoop();
  }

  void draw();

private:

  /* put your data here */ 

private:
  static MyGame* g_game; //< a single global pointer to your game
  static void glut_draw();
};


MyGame* MyGame::g_game = 0;

MyGame::MyGame(int argc, char* argv[])
{
  assert(g_game);
  glutInit(&argc, argv);

  /* do all the usual glutCreateWindow / glutInitDisplayMode stuff here */

  // attach the 
  glutDisplayFunc(glut_draw);
  glutMainLoop();
}

// use this static method to thunk into the member function draw()
void MyGame::glut_draw()
{
  g_game->draw();
}

void MyGame::draw()
{
  glClear(GL_COLOR_BUFFER_BIT);

  // you now have access to all the member variables of the MyGame class.

  glutSwapBuffers();
}

对于奖励积分,您可以将 draw() 声明为虚拟,并将所有多余的东西隐藏在一个基类中。

【讨论】:

  • 谢谢,但我找到了替代方案。我使用了一个结构并将其地址分配给 window 属性,以便我可以从所有代码中获取它。我用这个: void * glutGetWindowData(); glutSetWindowData(void *data);
猜你喜欢
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 2018-01-07
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多