In this tutorial we will be extending the simple game “Drop”, made in the previous tutorial. We will be adding a menu screen and a couple of features to make this game a little more fully featured.

Let’s get started with an introduction to a few more advanced classes in libGDX.

The Screen interface

Screens are fundamental to any game with multiple components. Screens contain many of the methods you are used to from ApplicationListener objects, and include a couple of new methods: show and hide, which are called when the Screen gains or loses focus, respectively. Screens are responsible for handling (i.e., processing and rendering) one aspect of your game: a menu screen, a settings screen, a game screen, etc.

The Game Class

The Game class is responsible for handling multiple screens and provides some helper methods for this purpose, alongside an implementation of ApplicationListener for you to use. Together, Screen and Game objects are used to create a simple and powerful structure for games.

We will start with creating a Game object, whose create() method will be the entry point to our game. Let’s take a look at some code:

  1. package com.badlogic.drop;
  2. import com.badlogic.gdx.Game;
  3. import com.badlogic.gdx.graphics.g2d.BitmapFont;
  4. import com.badlogic.gdx.graphics.g2d.SpriteBatch;
  5. public class Drop extends Game {
  6. public SpriteBatch batch;
  7. public BitmapFont font;
  8. public void create() {
  9. batch = new SpriteBatch();
  10. font = new BitmapFont(); // use libGDX's default Arial font
  11. this.setScreen(new MainMenuScreen(this));
  12. }
  13. public void render() {
  14. super.render(); // important!
  15. }
  16. public void dispose() {
  17. batch.dispose();
  18. font.dispose();
  19. }
  20. }

We start the application with instantiating a SpriteBatch and a BitmapFont. It is a bad practice to create multiple objects that can be shared instead (see DRY). The SpriteBatch object is used to render objects onto the screen, such as textures; and the BitmapFont object is used, along with a SpriteBatch, to render text onto the screen. We will touch more on this in the Screen classes.

Next, we set the Screen of the Game to a MainMenuScreen object, with a Drop instance as its first and only parameter.

A common mistake is to forget to call super.render() with a Game implementation. Without this call, the Screen that you set in the create() method will not be rendered if you override the render method in your Game class!

Finally, another reminder to dispose of your (heavy) objects! Some further reading on this can be found here.

The Main Menu

Now, let’s get into the nitty-gritty of the MainMenuScreen class.

  1. package com.badlogic.drop;
  2. import com.badlogic.gdx.Gdx;
  3. import com.badlogic.gdx.Screen;
  4. import com.badlogic.gdx.graphics.OrthographicCamera;
  5. public class MainMenuScreen implements Screen {
  6. final Drop game;
  7. OrthographicCamera camera;
  8. public MainMenuScreen(final Drop game) {
  9. this.game = game;
  10. camera = new OrthographicCamera();
  11. camera.setToOrtho(false, 800, 480);
  12. }
  13. //...Rest of class omitted for succinctness.
  14. }

In this code snippet, we make the constructor for the MainMenuScreen class, which implements the Screen interface. The Screen interface does not provide any sort of create() method, so we instead use a constructor. The only parameter for the constructor necessary for this game is an instance of Drop, so that we can call upon its methods and fields if necessary.

Next, the final “meaty” method in the MainMenuScreen class: render(float)

  1. public class MainMenuScreen implements Screen {
  2. //public MainMenuScreen(final Drop game)....
  3. @Override
  4. public void render(float delta) {
  5. ScreenUtils.clear(0, 0, 0.2f, 1);
  6. camera.update();
  7. game.batch.setProjectionMatrix(camera.combined);
  8. game.batch.begin();
  9. game.font.draw(game.batch, "Welcome to Drop!!! ", 100, 150);
  10. game.font.draw(game.batch, "Tap anywhere to begin!", 100, 100);
  11. game.batch.end();
  12. if (Gdx.input.isTouched()) {
  13. game.setScreen(new GameScreen(game));
  14. dispose();
  15. }
  16. }
  17. // Rest of class still omitted...
  18. }

The code here is fairly straightforward, except for the fact that we need to call game’s SpriteBatch and BitmapFont instances instead of creating our own. game.font.draw(SpriteBatch, String, float, float), is how text is rendered to the screen. libGDX comes with a pre-made font, Arial, so that you can use the default constructor and still get a font.

We then check to see if the screen has been touched, if it has, then we check to set the games screen to a GameScreen instance, and then dispose of the current instance of MainMenuScreen. The rest of the methods that are needed to implement in the MainMenuScreen are left empty, so I’ll continue to omit them (there is nothing to dispose of in this class).

The Game Screen

Now that we have our main menu finished, it’s time to finally get to making our game. We will be lifting most of the code from the original game as to avoid redundancy, and avoid having to think of a different game idea to implement as simply as Drop is.

  1. package com.badlogic.drop;
  2. import java.util.Iterator;
  3. import com.badlogic.gdx.Gdx;
  4. import com.badlogic.gdx.Input.Keys;
  5. import com.badlogic.gdx.Screen;
  6. import com.badlogic.gdx.audio.Music;
  7. import com.badlogic.gdx.audio.Sound;
  8. import com.badlogic.gdx.graphics.OrthographicCamera;
  9. import com.badlogic.gdx.graphics.Texture;
  10. import com.badlogic.gdx.math.MathUtils;
  11. import com.badlogic.gdx.math.Rectangle;
  12. import com.badlogic.gdx.math.Vector3;
  13. import com.badlogic.gdx.utils.Array;
  14. import com.badlogic.gdx.utils.ScreenUtils;
  15. import com.badlogic.gdx.utils.TimeUtils;
  16. public class GameScreen implements Screen {
  17. final Drop game;
  18. Texture dropImage;
  19. Texture bucketImage;
  20. Sound dropSound;
  21. Music rainMusic;
  22. OrthographicCamera camera;
  23. Rectangle bucket;
  24. Array<Rectangle> raindrops;
  25. long lastDropTime;
  26. int dropsGathered;
  27. public GameScreen(final Drop game) {
  28. this.game = game;
  29. // load the images for the droplet and the bucket, 64x64 pixels each
  30. dropImage = new Texture(Gdx.files.internal("droplet.png"));
  31. bucketImage = new Texture(Gdx.files.internal("bucket.png"));
  32. // load the drop sound effect and the rain background "music"
  33. dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
  34. rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));
  35. rainMusic.setLooping(true);
  36. // create the camera and the SpriteBatch
  37. camera = new OrthographicCamera();
  38. camera.setToOrtho(false, 800, 480);
  39. // create a Rectangle to logically represent the bucket
  40. bucket = new Rectangle();
  41. bucket.x = 800 / 2 - 64 / 2; // center the bucket horizontally
  42. bucket.y = 20; // bottom left corner of the bucket is 20 pixels above
  43. // the bottom screen edge
  44. bucket.width = 64;
  45. bucket.height = 64;
  46. // create the raindrops array and spawn the first raindrop
  47. raindrops = new Array<Rectangle>();
  48. spawnRaindrop();
  49. }
  50. private void spawnRaindrop() {
  51. Rectangle raindrop = new Rectangle();
  52. raindrop.x = MathUtils.random(0, 800 - 64);
  53. raindrop.y = 480;
  54. raindrop.width = 64;
  55. raindrop.height = 64;
  56. raindrops.add(raindrop);
  57. lastDropTime = TimeUtils.nanoTime();
  58. }
  59. @Override
  60. public void render(float delta) {
  61. // clear the screen with a dark blue color. The
  62. // arguments to clear are the red, green
  63. // blue and alpha component in the range [0,1]
  64. // of the color to be used to clear the screen.
  65. ScreenUtils.clear(0, 0, 0.2f, 1);
  66. // tell the camera to update its matrices.
  67. camera.update();
  68. // tell the SpriteBatch to render in the
  69. // coordinate system specified by the camera.
  70. game.batch.setProjectionMatrix(camera.combined);
  71. // begin a new batch and draw the bucket and
  72. // all drops
  73. game.batch.begin();
  74. game.font.draw(game.batch, "Drops Collected: " + dropsGathered, 0, 480);
  75. game.batch.draw(bucketImage, bucket.x, bucket.y, bucket.width, bucket.height);
  76. for (Rectangle raindrop : raindrops) {
  77. game.batch.draw(dropImage, raindrop.x, raindrop.y);
  78. }
  79. game.batch.end();
  80. // process user input
  81. if (Gdx.input.isTouched()) {
  82. Vector3 touchPos = new Vector3();
  83. touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
  84. camera.unproject(touchPos);
  85. bucket.x = touchPos.x - 64 / 2;
  86. }
  87. if (Gdx.input.isKeyPressed(Keys.LEFT))
  88. bucket.x -= 200 * Gdx.graphics.getDeltaTime();
  89. if (Gdx.input.isKeyPressed(Keys.RIGHT))
  90. bucket.x += 200 * Gdx.graphics.getDeltaTime();
  91. // make sure the bucket stays within the screen bounds
  92. if (bucket.x < 0)
  93. bucket.x = 0;
  94. if (bucket.x > 800 - 64)
  95. bucket.x = 800 - 64;
  96. // check if we need to create a new raindrop
  97. if (TimeUtils.nanoTime() - lastDropTime > 1000000000)
  98. spawnRaindrop();
  99. // move the raindrops, remove any that are beneath the bottom edge of
  100. // the screen or that hit the bucket. In the later case we increase the
  101. // value our drops counter and add a sound effect.
  102. Iterator<Rectangle> iter = raindrops.iterator();
  103. while (iter.hasNext()) {
  104. Rectangle raindrop = iter.next();
  105. raindrop.y -= 200 * Gdx.graphics.getDeltaTime();
  106. if (raindrop.y + 64 < 0)
  107. iter.remove();
  108. if (raindrop.overlaps(bucket)) {
  109. dropsGathered++;
  110. dropSound.play();
  111. iter.remove();
  112. }
  113. }
  114. }
  115. @Override
  116. public void resize(int width, int height) {
  117. }
  118. @Override
  119. public void show() {
  120. // start the playback of the background music
  121. // when the screen is shown
  122. rainMusic.play();
  123. }
  124. @Override
  125. public void hide() {
  126. }
  127. @Override
  128. public void pause() {
  129. }
  130. @Override
  131. public void resume() {
  132. }
  133. @Override
  134. public void dispose() {
  135. dropImage.dispose();
  136. bucketImage.dispose();
  137. dropSound.dispose();
  138. rainMusic.dispose();
  139. }
  140. }

This code is almost 95% the same as the original implementation, except now we use a constructor instead of the create() method of the ApplicationListener, and pass in a Drop object, like in the MainMenuScreen class. We also start playing the music as soon as the Screen is set to GameScreen. Moreover, we added a string to the top left corner of the game, which tracks the number of raindrops collected.

Note that the dispose() method of the GameScreen class is not called automatically, see the Screen API. It is your responsibility to take care of that. You can call this method from the dispose() method of the Game class, if the GameScreen class passes a reference to itself to the Game class. It is important to do this, else GameScreen assets might persist and occupy memory even after exiting the application.

And that’s it, you have the complete game finished. That is all there is to know about the Screen interface and abstract Game Class, and all there is to creating multifaceted games with multiple states. The full Java code can be found here. If you are developing in Kotlin, take a look here for the full code.

The Future

After this tutorial you should have a basic understanding how libGDX works and what to expect going forward. Some things can still be improved, like using the Memory Management classes to recycle all the Rectangles we have the garbage collector clean up each time we delete a raindrop. OpenGL is also not too fond if we hand it too many different images in a batch (in our case it’s OK as we only had two images). Usually one would put all those images into a single Texture, also known as a TextureAtlas. In addition, taking a look at Viewports will most certainly prove useful. Viewports help dealing with different screen sizes/resolutions and decide, whether the screen’s content needs to be stretched/should keep its aspect ratio, etc.

To continue learning about libGDX we highly recommend reading our wiki and checking out the demos and tests in our main GitHub repository. If you have any questions, join our official Discord server, we are always glad to help!

The best practice is to get out there and do it, so farewell and happy coding!