Full LibGDX Game Tutorial – Project setup

Box2d Full Game Tutorial

Sharing is caring!

Full LibGDX Game Tutorial

This Full LibGDX Game Tutorial is a full-blown game development tutorial covering all aspects of creating a game using Box2D in libGDX. It is aimed at those people who want to create games but have no knowledge about programming at all. Not only will we cover techniques used to create games but also cover the basics of using java as a language to make games. We will go into how to load images, sounds, music, effects etc with an asset manager which will get rid of the images when they are no longer needed. we will cover how to layout your project so you keep all the different parts in their own group such as game logic on one area, loading in another and rendering in another.

Things we will not cover in this tutorial are being a good programmer, only you can become a good programmer by learning, how to get your game on google play, steam or the app store. That is more marketing than it is creating a game and will not be covered.

Concepts

Before we start I will go over a few concepts that relate to this project: LibGDX is a framework that allows you to code applications in java and allows you to export your application to run on other platforms such as your windows/linux desktop, Android(Android phones), IOS (IPhones iPad) and HTML(in a web browser). This means you only have to write your code once and it will work on those platforms instead of having to make several projects for each platform.

Java is an object-oriented language. This means when you write some code you are writing the blueprint of an object and when your application is run the code will become an object that has its own set of data and actions that can be accessed. Changes to that object will not affect other objects made from the same blueprints without special code. For example, you could write a class called Car and you could make 3 cars. One blue, one green and one yellow. Changing the colour of the blue car will not change the colour or the green or yellow car as they are separate objects.

Java uses a package system to keep groups of code together e.g. All things relating to images would be kept in the image package and all things related to saving files would be in the IO(InputOuput) package. In order to save a file you would need to import both the images package and the IO package.

I think that covers the basics for now, additional information will be given when they pop up in the tutorial.

Creating the project

The first thing we need to do is to setup a new LibGDX Project. If you don’t know how to create a LibGDX project you can read this guide on how to use the LibGDX Project Generator tool to create projects for eclipse. Now we know how to make a project we should make one, and name the main class Box2DTutorial. This will help keep your project in line with this guide. Make sure you add the Box2D extension or you will not be able to import the classes needed for this guide. Below is a screenshot of the settings I used to create my project. NOTE: I have intentionally left out Ai as I will go through adding this via gradle later in this tutorial but you can ad it now if you ae already capable of adding via gradle.

Full LibGDX Game My Project setup settings

The first thing I do with my games is separate the game into an orchestrator(the boss class), a model for game data and logic processing, views for displaying and rendering and controllers for mapping user input to methods in the model. Our main class will be Box2DTutorial it will be our Orchestrator and be the parent for our upcoming model, views and controllers.

Our base structure will be:

  • Box2DTutorial – This is our Orchestrator
  • AppPreferences – our preferences class
  • Box2DTutorialModel – This is our Model which contains the logic
    • Views
      • LoadingScreen – initial screen to show loading screen.
      • MenuScreen – a menu screen our second screen to show.
      • MainScreen – the screen which shows the game play.
      • PreferencesScreen – shows the preferences and allows them to be changed.
      • EndScreen – show the end game credits etc.
    • Controllers
      • KeyboardController- maps controls to model methods (one for each control type, controller, keyboard, phone accelerometer etc)

Now we have decided on our base structure we can start coding our classes.

Coding

If you followed this guide your main class should be called Box2DTutorial, this is the class we’re going to edit first. The first thing to do is remove the default methods and then change our orchestrator from extending the default class to extending a game class. A game class is used to delegate between different screens. As were going to use 5 screens this class will suit our needs.

The orchestrator should now look like this:

Now we have our orchestrator extending the game class we want it to be able to switch between screens, but we have no screens. Yeah, we need to make these screens. The problem is we don’t have our views package set up yet to place our screens in. Well in eclipse we can just add a new class and set it to the views package and that package will be created with the class. So, let’s do that.

Right click on your Box2DTutorial class and click new > class. This will bring up the add class window. We will add the LoadingScreen class first so in the Name field enter LoadingScreen and in the package field enter blog.gamedevelopment.box2dtutorial.views (if your package structure is different e.g not blog.development, just add .views to the end of the current package text) and click finish. This will create a new default class called LoadingScreen and put it in the package views.

Now we have a loading screen but it doesn’t know how to be a screen because it’s just an empty class. Let’s fix that now. Open your newly created LoadingScreen class and make it extend the Screen class. You will see Screen get highlighted in red, if you hover over it, you will see the error and can view possible options to fix it. We want to import com.badlogic.gdx.Screen, we then get another red highlight on the class name. This is saying the methods for Screen have not been implemented so let’s “Add unimplemented methods”. This automagically fixes our class. Your LoadingScreen should now look like this code:

One down, repeat this for the other 4 screens MenuScreen, MainScreen, EndScreen and PreferencesScreen.

Changing screen

Now we have all our screens we need a way to swap between them. In order to do that we will create a new method called changeScreen in our orchestrator.

This method relies on 4 constants MENU, PREFERENCES, APPLICATION and ENDGAME, these must be defined in our orchestrator as well as the 5 screens. We define the 4 constants using the final static modifiers and our 5 fields for the screens shown in the code below:

Now we have our screens and our changeScreen method we need to set the default screen when the application opens. This is done in the create method. The Game class already has a method called create which is run when the game creates the class, we want to use this method so we use the @Override command to change the default create method to the one we will define now. Note: If you do not @Override the create method then the method will not run. So our create method looks like this:

We have successfully changed the Game class’s create method to create a new LoadingScreen and then set the current screen to display it. At the moment we have no images, sounds or music to load (but we will) so our loading screen can just say “Hey! I’m done loading”. There’s a problem, our LoadingScreen doesn’t know how to tell our orchestrator it’s done loading. In order to do that the LoadingScreen needs to know about the orchestrator, in fact, all our screens need to know about our orchestrator in order to tell it they are done doing what they’re doing. So let’s add a way for our screens to tell the orchestrator they’re done.

We need to add a reference to our orchestrator in each of our screens. This is done by passing the orchestrator object to the screen when we create them. So in our each of our screens, we add a constructor. A constructor is a method that is called when the class is created and can take arguments. To create a constructor you use the classes name as the method name and do not add a return type. So our LoadingScreen constructor would look like this:

Now a blank constructor isn’t going to do much so we need to add our orchestrator argument and assign it to a field in our class so we can access it later.

Do this for each of the screens remembering to change the constructor name to the name of the class. This will allow all our screens to tell the orchestrator when they’re done. Now the screens have been updated the orchestrator needs to be updated to fill in the arguments requested in the constructor of the screens. So change our orchestrator changeScreen method to the following:

Also in the orchestrator replace the loadingScreen code to this

The word “this” is a special word in Java used to represent the current object. As were in the Box2DTutorial class it will reference Box2DTutorial objects. Now all our screens know who the orchestrator is we can finally update our LoadingScreen class to tell the orchestrator they’re done and they should proceed to load the menu screen. In our render method of our LoadingScreen class we need to add the following code:

Creating a Menu screen

So we’re now changing to the menu screen but our menu screen doesn’t do anything yet. We need some buttons. There’s plenty of ways of adding a GUI to a screen including simple images and listening to clicks to using the inbuilt scene-2d. We will be using Scene-2D to create our GUI as it’s relatively simple to use and pretty powerful.

Before we begin your MenuScreen class should look like this:

The first thing we will add is a stage. This is the controller and will react to inputs from the user. In our constructor we add the following code:

We create a new stage with a new ScreenViewport as an argument. This will produce errors and will require you to import the ScreenViewport as you did previously with the LoadingScreen error. You will also get an error from the stage word and the solution is to add a new field. From now on in this guide, I will not prompt you to import new classes used or add fields as these errors are pointed out by eclipse and show their solutions. I will, however, point out errors which require more detailed solutions. We also set the input processor for this screen to the stage. This tells the screen to send any input from the user to the stage so it can respond.

Now the stage is in our class, we will need to tell it to act and draw. If we did not put in this act and draw section the stage would not perform actions after user input and it would not draw the items held within it.

So now we have our stage that will draw its contents, we need to add items for it to draw. Those items are the buttons and the table. We will add 3 buttons to our stage using the table to lay them out in the middle of the screen. The table is like an Excel sheet where you start with one cell and can add a new column or row until you have all the cells you need, unlike Excel you can specify layout properties such as size, padding and fill style irrespective of other cells in the column or row. So, in our show method, let’s add our table to hold out buttons.

We added our table to our stage, now we create some buttons.

In our button code, we have added a new item called a skin. A Skin is libgxd’s way of keeping GUI elements like button textures, fonts and other GUI layout parameters all in one file. In order to use a skin we must first add the images and JSON files that make the skin into our project. To add a skin to your project go to https://github.com/czyzby/gdx-skins and download the skin you want to use for this project. I chose the glassy skin. Once downloaded you will end up with a folder called skin with some .fnt, .atlas, .json and .png files. This skin folder should be placed in your android asset folder. For example, my folder location is:

Full LibGDX Game Folder Location

 

Now the skin is added to your project folder you need to refresh it in eclipse so it knows to add it to future runs. To do that right click your android project and click the refresh option. Now our skin is added and ready to use in our buttons we need to add our buttons to the table.

In the code above we use “table.add(newGame).fillX().uniform();” This adds our first button to the table and sets it to fill out on the x axis (horizontally) and make it uniform with other cells in this column (currently none). So now we have a table with a single cell containing a button and nothing else. Next we add “table.row().pad(10,0,10,0);” This mean the next table.add() will add their items to the next row instead of suffixing them to the current row. We also set the padding of the new row to 10 pixels top, 0 left, 10 bottom and 0  right. Next, we add our second button similar to the first button and again add a new row, this time with no padding as our previous row is already padding the bottom 10 pixels and finally, we add our last button.

The image below shows how we just created a menu using the row and add methods.

Full LibGDX Game Table Layout

You can now run your project and you should be shown and image similar to the one above (minus the tutorial text). Cool right? Notice any issues? yeah, our buttons don’t stay in the centre when we change the size of our window and if we maximise it we get some flickering issue with the buttons. The centring of the buttons is fixed by updating our stage every time the window is resized. So in our resize method, we add this code:

This tells the stage that the screen size has changed and the viewport should be recalculated. The true boolean, the last argument is what tells the camera to recenter. So that’s the first issue fixed, now how do we fix the flickering. Well, the flickering is caused by the image not being clear each time it is drawn. We must tell it clear the screen before we start drawing the next screen. This is done in our render method before we draw anything so our render method should now look like this:

We finally have something to show for all our work. Yay.

Part 2 of our Full LibGDX Game tutorial will go into how to add actions to your buttons and adding preferences.

Contents Preferences And Menu →

Sharing is caring!

32 Replies to “Full LibGDX Game Tutorial – Project setup”

  1. Nice one man, thanks.

  2. Your link to Part 2 isn’t working. The same as some other links inside your tutorial!

    1. Hi Francis, Thanks for your comment. The links have now been fixed.

  3. Hey, just wanted to let you know– on all your subsequent tutorial parts, the link you have in their opening paragraphs that come back to this first page are broken. I had to kinda scour until this page popped up in your ‘popular posts’ list, instead of just clicking the hyperlink.
    I have it bookmarked now, though, and look forward to reading through it beginning to current end. Thanks!

    1. Hi Craig,
      Thanks for your comment. The links should all be fixed now.

  4. I get JSON does not accept the identifiers in my glassy-ui.json file

  5. I just wanted to mention for readers that the menu table does not appear as it is told in this article until you apply the last “render” function in MenuScreen.

  6. this works for android ?

    1. It will work on android but will not look very good as the screen size is aimed at desktop users. It was mainly created to show the game development process, however, a few tweeks on screen sizes, object placement etc should be able to make it work on android.

  7. Thank. I need to turn my Android app to cross-platform. this tutorial has been of great help.

  8. For me, first it didn’t work. Then I found out that render method of MenuScreen is not called. I did a little bit of research and added
    super.render();
    to Box2DTutorial class’s render method. I saw it from here https://github.com/libgdx/libgdx/wiki/Extending-the-simple-game

    1. staying true to your name – thanks.

    2. That was super helpful, my screen was staying black all the time and I couldnt figure out why 🙂

  9. If u are using Android Studio in order to see the menu screen table and its buttons u need to go to Box2DTutorial Class and in render method delete everything then add this code:
    @Override
    public void render () {
    super.render();
    }
    it allows all classes that implements Screen to render.
    Also in dispose method, dispose super:
    @Override
    public void dispose () {
    batch.dispose();
    super.dispose();
    }

    1. where is the batch created? I suppose it hase to be created before being disposed, right?

  10. Thank you for the tutorial!
    It’s immensely helpful!
    If you could change the site theme to a dark gray like in Android Studio.
    It would ease the strain on the viewer’s eyes.

    1. Thanks for your comment. I usually just have a bookmark in my browser that sets the background to light grey. Just set the bookmark location to
      javascript:(function(){window.document.body.style.backgroundColor=”#DDDDDD”})();
      Then all you have to do is click the bookmark and the background changes 🙂

  11. Would you be able to post the full source code for the Box2DTutorial class as it would look at the end of this tutorial? Mine isn’t working and I’d like to compare the two.
    Thanks!

    1. The tutorial is not complete yet as it is being created as I work through the game. Unfortunately, this will not be completed anytime soon with the amount of work I have on at the moment.

  12. This tutorial is the most complete and easiest to follow. Thank you very much.

  13. this no longer works in Android studio.

  14. Please respond!
    Hello. I used a few ideas from your tutorials in a program for my academic degree project.
    Mainly – the idea (not the code) to divide views, control and logic packages in the way you did it, AppPreferences class and public static integers for screen change in the main Game class. Some names in the project might be similiar to yours, too.
    Should I give you a credit in any way? I’m not trying to be a bad person and steal your work, but it is really, really not advisible to leave links to blogs in such work, because they aren’t “scientific” enough, or so I was told. Can I credit you in any other way, if it is necessary? I could probably slip in “John Day from Game Develompent Blog” somewhere, would this be ok?

    1. Hi, I don’t require any credit as this blog is a hobby and intended to help other develop their skills. If you want to add a citation to my work to reduce the risk of plaigerism too that is fine.

      1. I already sent my work. I mentioned you! I made a “special thanks” section in the licenses file for it.
        Thank you very much for your tutorial.

  15. Thanks for this.
    I was having trouble with my JSON file and got it to work and wanted to share. Go to the raw text and “save as”. Don’t save the fonts or atlas as .txt files if you have your preferences set to automatically add extensions. They all work once I got them properly imported to my assets folder.

  16. Screen just stays black, tried all the comments from everyone else. No joy.
    Where is the camera?

  17. Where am i supposed to find the android asset folder? Also, where do i put the skin if I’m not making for android?

    1. IF its not for android use the core folder

  18. How to become a video game developer?

  19. Thanks for the great tutorial.

    I tried to download the source on the https://www.gamedevelopment.blog/downloads/ page and the source links are not working

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.