Wyatt Wyatt - 6 months ago 44
Android Question

Libgdx | How to create a splash screen?

I am wondering what the best way to create a splash screen is (When you start game, the companies logo animated). I have create a .mp4 splash screen in after effects, but can't find a way to display it in libgdx. What's the best way to create a splash screen? Can you use an .mp4 file and play it or not?

Answer

There is a pretty easy way to implement a splash screen without creating a new activity. The way to set a time for your splash screen is to take the difference from when your app was first started (in the create()) method to the current time. Declare a start time variable directly in your class:

long startTime;

You can get the time elapsed using TimeUtils.millis(). Put this code into your create() method like so:

@Override
public void create() {
    // Initialize all your other variables here
    startTime = TimeUtils.millis();
}

Then in your render() method (which is running all the time), add the code to check for the elapsed time. Here is an example:

@Override
public void render() {
    if(TimeUtils.millis() - startTime != 10000) {
        // 10 seconds haven't passed yet
        batch.begin();
        // Creates a white background
        Gdx.gl.glClearColor(1f, 1f, 1f, 1);
        // Draw your animation here
        batch.end();
    } else {
        // Put real game code here
    }
}

The code above basically checks to see if 10 seconds haven't passed. If so, it displays your animation. If not, put all your regular code for after the screen has loaded.

Unfortunately, there is no direct way to display a .mp4 file in Libgdx. This might be a problem for your app. One solution is to convert your .mp4 file to a .gif (animated image file), using this website. You can then extract all those frames to many image files using this .gif splitter. If you have another way to extract your frames from your video use that method. Once you do though, loop through all those images to create your animation. Here is what you could do:

Texture[] textures = new Texture[NUMBER_OF_FRAMES];
for(Texture t : textures) {
    batch.draw(t,
            Gdx.graphics.getWidth() / 2 - t.getWidth()/2,
            Gdx.graphics.getHeight() / 2 - t.getHeight()/2);
}

Of course, you could always just use one static image, which is much easier to display, and put that in your render() method. Regardless of your method, hope this answer helps!