Search code examples
androidopengl-esthread-sleepgame-loop

Creating a game loop (sleep time help)


I've been using this tutorial to create a game loop.

In the section marked "FPS dependent on Constant Game Speed" there is some example code that includes a Sleep command

I googled the equivalent in java and found it is

Thread.sleep();

but it returns an error in eclipse

Unhandled exception type InterruptedException

What on earth does that mean.

And also I was wondering what the

update_game();
display_game(); 

methods may contain in an opengl-es game (ie: where is the renderer updated and what sort of things go on in display_game();

I am currently using a system that uses the GLSurfaceView and GLSurfaceRenderer features

Here is my adaptation of the code in the tutorial

public Input(Context context){
    super(context);
    glSurfaceRenderer = new GLSurfaceRenderer();
    checkcollisions = new Collisions();
    while (gameisrunning) {
    setRenderer(glSurfaceRenderer);


    nextGameTick += skipTicks;
    sleepTime = nextGameTick - SystemClock.uptimeMillis();
    if(sleepTime >= 0) {
        Thread.sleep(sleepTime);
    }else{
        //S*** we're behind
    }

    }

This is called in my GLSurfaceView although I'm not sure whether this is the right place to implement this.


Solution

  • Looks like you need to go through a couple of tutorials on Java before trying to tackle android game development. Then read some tutorials on Android development, then some more general game development tutorials. (Programming is a lot of reading.)

    Thread is throwing an exception when it gets interrupted. You have to tell Java how to deal with that.

    To answer your question directly, though, here's a method that sleeps till a specific time:

    private void waitUntil(long time) {
        long sleepTime = time - new Date().getTime();
    
        while (sleepTime >= 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                // Interrupted. sleepTime will be positive, so we'll do it again.
            }
            sleepTime = time - new Date().getTime();
        }
    }
    

    You should understand at least this method before continuing on game development.