Game Development Reference
In-Depth Information
public void
onDrawFrame(GL10 gl) {
GLGameState state =
null
;
synchronized
(stateChanged) {
state =
this
.state;
}
if
(state == GLGameState.
Running
) {
float
deltaTime = (System.
nanoTime
()-startTime) / 1000000000.0f;
startTime = System.
nanoTime
();
screen.update(deltaTime);
screen.present(deltaTime);
}
if
(state == GLGameState.
Paused
) {
screen.pause();
synchronized
(stateChanged) {
this
.state = GLGameState.
Idle
;
stateChanged.notifyAll();
}
}
if
(state == GLGameState.
Finished
) {
screen.pause();
screen.dispose();
synchronized
(stateChanged) {
this
.state = GLGameState.
Idle
;
stateChanged.notifyAll();
}
}
}
The
onDrawFrame()
method is where the bulk of all the work is performed. It is called by the
rendering thread as often as possible. Here, we check what
state
our game is in and react
accordingly. As
state
can be set on the
onPause()
method on the UI thread, we have to
synchronize the access to it.
If the game is running, we calculate the delta time and tell the current
Screen
to update and
present itself.
If the game is paused, we tell the current
Screen
to pause itself as well. We then change the
state to
GLGameState.Idle
, indicating that we have received the pause request from the UI
thread. Since we wait for this to happen in the
onPause()
method in the UI thread, we notify the
UI thread that it can now truly pause the application. This notification is necessary, as we have
to make sure that the rendering thread is paused/shut down properly in case our
Activity
is
paused or closed on the UI thread.
If the
Activity
is being closed (and not paused), we react to
GLGameState.Finished
. In this case,
we tell the current
Screen
to pause and dispose of itself, and then send another notification to
the UI thread, which waits for the rendering thread to shut things down properly.