user3246056
user3246056

Reputation: 23

Delaying actions

Im brand new to this Android game development, and i am currently trying to create a platform game. Is there a way to make certain actions (such as changing variable values) have a few second delay without the delaying mechanism halting eveything else? i have already tried

new Thread(){
public void run(){
    try {
        Thread.sleep(2000);
        //variable value change
    } catch (InterruptedException e) {
        e.printStackTrace();
        }
    }
}.start();

method which i found, but it seems like this method stops any background music that is running with it. Ive also tried the Handler method but it seems to crash the game. I am using libgdx framework.

Upvotes: 1

Views: 142

Answers (2)

nstosic
nstosic

Reputation: 2614

If you plan on doing OpenGL game (I encourage you to), you have the Renderer class which has built int methods: onDrawFrame(GL10 gl), onSurfaceChanged(GL10 gl), onSurfaceCreated(GL10 gl), the one you're interested in is onDrawFrame(GL10 gl).

So, the template of your class that extends Renderer should be like this:

public class CustomRenderer extends Renderer {
    @Override
    public void onDrawFrame(GL10 gl) {
        try {
            Thread.sleep((float)(1000/60)); // 1000 milliseconds divided by 60 so you get 60fps
            //Your code here
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onSurfaceChanged(GL10 gl) {
        //Your code here
    }
    @Override
    public void onSurfaceCreater(GL10 gl) {
        //Your code here
    }
}

Upvotes: -2

noone
noone

Reputation: 19796

You have to understand that your game is running in an endless loop. Usually you will endlessly get your render(float deltaTime) called by LibGDX.

You could either just do it yourself like this:

public void render(float deltaTime) {
    countDown -= deltaTime;
    if (countDown <= 0) {
        doSomething();
    }
}

Or you could use the Timer class of LibGDX instead like this:

float delay = 1; // seconds

Timer.schedule(new Task(){
    @Override
    public void run() {
        // Do your work
    }
}, delay);

Upvotes: 3

Related Questions