- Code: Select all
//Default constructor for our GameScreen class.
public GameScreen()
{
//create a new Thread on this Runnable and start it immediately
new Thread( this ).start();
}
/*
* run() method defined in the Runnable interface, called by the
* Virtual machine when a Thread is started.
*/
public void run()
{
}
Now when we construct our GameScreen it will create and start a new Thread which triggers a call to our run() method.
We want our main loop to be called at a fixed rate, for this example lets set the rate to 15 times per second. (Although it is impossible to give an exact performance figure that will apply to all games, 15fps is a reasonably indicative average to start off with)
Within the run() method of our class we implement the timing logic for our main loop:
- Code: Select all
/*
* run() method defined in the Runnable interface, called by the
* Virtual machine when a Thread is started.
*/
public void run()
{
//set wanted loop delay to 15th of a second
int loopDelay = 1000 / 15;
while( true )
{
//get the time at the start of the loop
long loopStartTime = System.currentTimeMillis();
//call our tick() fucntion which will be our games heartbeat
tick();
//get time at end of loop
long loopEndTime = System.currentTimeMillis();
//caluclate the difference in time from start til end of loop
int loopTime = (int)(loopEndTime - loopStartTime);
//if the difference is less than what we want
if( loopTime < loopdelay )
{
try
{
//then sleep for the time needed to fullfill our wanted rate
thread.sleep( loopdelay - looptime );
}
catch( exception e )
{
}
}
}
}
/*
* our games main loop, called at a fixed rate by our game thread
*/
public void tick()
{
}
To test our main loop lets make it change the colour of the background to a random colour every frame. We can use this opportunity to move the repaint() call to within our game loop.
- Code: Select all
/*
* Our games main loop, called at a fixed rate by our game Thread
*/
public void tick()
{
//get a random number within the RRGGBB colour range
colour = generator.nextInt() & 0xFFFFFF;
//schedule a repaint of the Canvas
repaint();
//forces any pending repaints to be serviced, and blocks until
//paint() has returned
serviceRepaints();
}
