I had a basic game loop provided for me for a project I had to do several months ago. I don't really understand what it is doing though, and why it works. Now I'm trying to work on my own project, and I want to be able to exit the game loop, and exit the program. I can't figure out how to do it. In my main function,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main(int argc, char ** argv)
{
Point topLeft(-200, 200);
Point bottomRight(300, -300);
Interfact ui(argc, argv, "Game", topLeft, bottomRight);
Game game(topLeft, bottomRight);
ui.run(callback, &game);
return 0;
}
void callBack(const Interface *pUI, void *p)
{
Game *pGame = (Game *)p;
pGame->advance();
pGame->handleInput();
pGame->draw();
}
I've shared what was provided for me. I've managed to change things to be able to create an end screen when the game has ended and stuff like that, but I really want to be able to exit the game altogether. I cannot figure out how to do it. How do I return from that callBack?
The callback will return as soon as the draw() call is done.
It's the ui.run call that needs to end at some point. So something, perhaps a variable inside Game, needs to indicate whether or not the game is ending, and ui.run needs to check for and handle that.
That's because that's implemented by the GLUT library. GLUT is pretty old and is meant to work with the early versions of OpenGL, but of course is still usable.
As the Red Book says, you cannot safely exit the main loop in GLUT. That’s just the way it is. There are alternatives to GLUT, like GLFW and SDL, or even the native platform API line Win32 or X. Don’t know if you can use them, but fact is that if you need to exit the main loop in GLUT, GLUT is not the windowing API you should use. You have to start looking for another API.
Apparently you can call glutLeaveMainLoop(), but that function is only available if you're using "freeGLUT" or "openGLUT".
I normally don't suggest this, but if you're working with a crappy interface, you can use exit(0); to end the program, if glutLeaveMainLoop() doesn't work. The problem with exit(0) is that it abruptly ends the program without calling destructors or cleaning up any other resources, but this can be fine in many cases.
Eh, just my opinion, but I think SFML has a pretty logical main event loop system, and has a clean interface that's pretty beginner friendly. You don't make OpenGL calls directly, it internally does in the library. I would suggest SFML if you're trying to make a simple 2D game. https://www.sfml-dev.org/index.php
If you are looking into specifically learning OpenGL, there are sites like http://www.opengl-tutorial.org/ that you can follow. I believe opengl-tutorial.org walks throw the basics of using GLFW.
(Note that you do not need to learn OpenGL if you just want to start making games; you can use a library which handles the calls for you.)