2

I have some trouble with the delay command.

I want to show my logo for 2 seconds and then go to the MainMenu screen. But what it does is it shows a black screen for a couple of seconds, and goes to the MainMenu (I can see my logo for about 1ms):

public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0.2f, 0);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    game.batch.setProjectionMatrix(camera.combined);

    game.batch.begin();
    game.batch.draw(PGSImage, 0, 0);
    game.batch.end();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
    }

    game.setScreen(new MainMenuScreen(game));
    dispose();
}

What am I doing wrong?

Pang
  • 9,564
  • 146
  • 81
  • 122
urban07
  • 61
  • 10

2 Answers2

2

You should not use such long methods as sleep() inside render() method because normally it is called 30 times per second (or even more frequently).

You can add timer to the show() method of your current Screen:

@Override
public void show() {
    super.show();

    float delay = 2; // seconds

    Timer.schedule(new Task(){
        @Override
        public void run() {
            game.setScreen(new MainMenuScreen(game));
        }
    }, delay);
}

It will be called once your first Screen is displayed and then it will change your Screen to MainMenuScreen after 2 seconds.

Here Timer is com.badlogic.gdx.utils.Timer.

You can also count time using delta parameter of the render() method. Take a look at this question for more details.

Community
  • 1
  • 1
Rara
  • 639
  • 9
  • 22
1

I am assuming you are calling render() from the UI Thread. This means that Thread.sleep() will pause the execution of the UI Thread for 2 seconds.

If you want to delay execution one option is to use the Handler class. Make sure you read about Handlers and memory leaks.

Emmanuel
  • 13,083
  • 4
  • 39
  • 53
  • To clarify this answer: it's libgdx, so the game is running on a dedicated GL thread, not the UI thread. But the problem is the same. Libgdx has an alternative to Handlers, the com.badlogic.gdx.utils.Timer class. – Tenfour04 Mar 09 '15 at 01:35