Search code examples
androidopengl-esgame-loop

Best way to make game loop for Android using OpengGLSurface


From what I've seen, if I wanna make a NON-opengl game loop what I can do is have a game thread that during the loop will update the game state (or game physics) and also update the graphics by locking a Canvas from a (normal) SurfaceView, doing the drawing via Canvas.drawXXX(...) methods and then unlocking it at which point the graphics get updated for the loop.

I don't really get how to do that when using GLSurfaceView and Renderer. From what I understand, I can no longer have my hand-made gameThread draw on demand as I had with the regular surface and it's Canvas, because now there's a rendering thread that will call Renderer.onDrawFrame() (on my implementation of the renderer class that I pass to the GLSurfaceView).

My question is then, what's a good way to make a game loop with GLSurfaceView and Renderer? Should I still make my separate game thread, but only handle game state (physics) updates in it and then use that game state in my implementation of Renderer.onDrawFrame() to actually draw graphics based on current state? Should I only use the Rendere's thread to also do state updates?


Solution

  • Well, as it turns out, best way to go is to use the thread provided by the GLSurface. The hook to it comes through an implementation of the Renderer interface. Effectively the Renderer's onDrawFrame() method can be considered analogous to a regular Thread's run() method. This kind of throws out the window the concept of a fixed updates per second paradigm (not really, but it's too convoluted to do in this context) but on the other hand you get optimal graphics updates.

    There's a great tutorial on Android and OpenGL here:

    http://insanitydesign.com/wp/projects/nehe-android-ports/