LibGDX Game Development Essentials Sample Chapter
LibGDX Game Development Essentials Sample Chapter
ee
Sa
pl
Acknowledgments
I would like to thank my parents and my wife, Dr. Nidhina Haridas, for inspiring me
to aim higher and try harder. My heartfelt thanks go to Eldhose P. Mathew, CEO of
Csharks, for allowing me to devote my professional time to work on this book. I would
also thank Anila Vincent, Meeta Rajani, and Madhunikita Chindarkar for supporting me
and all the other team members at Packt Publishing for giving me this opportunity.
A special thanks to Suryakumar for those brainstorming sessions and Kenney for the
open source art.
This book would not have been possible without the expertise of the technical reviewers
Tomasz Wojciechowski, Lvque Michel, Pavel Czempin, and Sudarshan Shetty. Thank
you guys.
I would also like to express my deep gratitude to Mario Zechner, without whom such
an incredible game framework would not have existed. Mario, you rock. Long
live LibGDX!
LibGDX Game
Development Essentials
Game development is one of the coolest things to do right now, be it as a hobby or as
a full-fledged career option. With the arrival of smartphones, tablets, and other smart
devices, games are leading all the app stores worldwide in terms of the number of
downloads and revenue. Games have opened up revenue streams worth millions of
dollars for not only game companies, but also for indies and single developers. App
stores support self-publishing and they are very indie-friendly, which means anyone
capable of creating a game can go ahead and publish their game and reap the benefits.
This book will help you with just that.
Developing a game is not an easy task, but with the right tools at our disposal it becomes
easier to develop a new game. Depending on the type of game, the platform, and prior
knowledge of the developer, there are different types of tools that can be used. This book
explores LibGDX, a Java-based game development framework that is primarily used to
develop 2D Android games. However, LibGDX is also capable of deploying to
Windows, Mac, Linux, iOS, Blackberry, and HTML5. Unity, Starling, Cocos2D,
Phaser, and OpenFL are some of the alternatives that you need to be aware of.
LibGDX (http://libgdx.badlogicgames.com) is an open source, Java-based
game development framework. It provides a setup for rapid prototyping and faster
iterations, with the capability to develop and debug on our desktop. It is the brainchild of
Mario Zechner, the author of Beginning Android Games. The team of LibGDX now has
15 people (https://github.com/orgs/libgdx/people). LibGDX is the
undisputed leader when it comes to creating Android 2D games that are performant
and universal.
This book aims to help you get started with game development using LibGDX. In this
book, you will create a simple game that is similar to Flappy Bird and learn about the
different aspects of game development. This book is bundled with the complete source
code of the working game Thrust Copter, along with other sample code relevant to
individual chapters. This book will help you to learn about game development, UI
creation, and data persistence. Once the game is ready, a chapter is dedicated to convert
it to a physics-based game using Box2D. Another chapter introduces basic 3D concepts,
tile maps, and other tools of the trade. The final chapters detail how to integrate various
third-party features and how to publish the game on various platforms.
The book does not try to teach you everything, but makes you ready to explore LibGDX
further and encourages you to explore the source code on your own. I would appreciate
it if you would support LibGDX once you are aware of its tremendous potential
(http://www.patreon.com/libgdx). Once you are done with this book, I would
urge you to read LibGDX Cross-platform Game Development Cookbook and Learning
LibGDX Game Development, both by Packt Publishing, to take your knowledge to the
next level.
Chapter 8, Saving Our Data, discusses the methods of file access that will help you
to preserve persistent data. We will implement a local leaderboard system with this
new knowledge. The TMX tile map is also introduced in this chapter.
Chapter 9, Finishing Our Android Game, adds analytics tracking, Google Ads,
Google Play services, leaderboard, and achievements to the game.
Chapter 10, Time to Publish, explains how to publish the game to different platforms
and app stores. Overlap2D, a great visual scene designer for LibGDX is also introduced
in this chapter.
Wiring Up
In this chapter, we will lay the ground work to facilitate our plan of creating a game
like Flappy Bird for multiple platforms, including Android, iOS, PC, and the Web.
You might wish to jump right in and start designing the game, but that is not the
case with LibGDX. There are lots of things to be done before we could start to code.
This chapter deals with the setting up of LibGDX for a cross-platform project. This is
done on a development environment configured for Android development. We will
cover the following topics:
Using the LibGDX Gradle setup app to create our first LibGDX project
Wiring Up
Getting started
Hope I didn't scare you with all those abbreviations. The majority of what we
will do in this chapter will only need to be done once, as it is required to set up
your development environment. Once it is done, we can forget about it and focus
on creating wonderful games. I will be using a Mac-based development setup
throughout this book, but the process is similar for Windows as well. The added
benefit that Mac provides is the ability to deploy to iOS as well. In the first part,
we will set up a Java development environment that will be very simple for all our
Java developers. This can be accomplished by setting up Eclipse, IntelliJ, or NetBeans
IDEs, but we will be focusing on Eclipse throughout this book. This does not mean
that this way is superior to the others but we've used it just because Eclipse is the
most widely used Java IDE and the majority of our potential readers should have
worked with Eclipse one way or another.
If you need to use another IDE, please check the LibGDX
wiki page at http://libgdx.badlogicgames.com/
documentation.html#gettingstarted.
[8]
Chapter 1
At the time of writing this book, the latest version is JDK 8u5 and the following
screenshot shows how the different versions are listed:
Once you download the relevant file, go ahead and install it on your machine.
Now, your machine is ready to be used for Java-based application development.
[9]
Wiring Up
On a Windows machine, you may need to set the value of the environment variable
JAVA_HOME to the installation path of the JDK after installation. We can check this
by running the following command in the command prompt:
C:\Users\admin>java -version
If the system displays the version details as follows, then Java is installed correctly:
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
Otherwise, we need to set up the Java environment variable. To find the correct
path, go to C:\Program Files (x86)\Java\. You should see a folder with the jdk
extension in its name. The complete path should be similar to the following one:
C:\Program Files (x86)\Java\jdk1.8.0_05
Follow the given steps on a 64-bit Windows machine with 32-bit Java installed to
set the environment variable:
1. Click on the Windows Start button, right-click on Computer, select
Properties, and open control panel system window.
2. Click on Advanced system settings on the left-hand side of the Control
Panel window to open the System Properties window.
3. Next, click on the Environment Variables button and click on the New...
button at the top that corresponds to User variables for <USERNAME>.
A window with the title New User Variable will appear.
4. Now, fill in the two text fields. Use JAVA_HOME in the Variable name field
and the JDK path you found out earlier in the Variable value field.
[ 10 ]
Chapter 1
Installing Eclipse
Next, we will need to install our IDE of choice: Eclipse. The latest version of Eclipse
can be found at http://www.eclipse.org/downloads/. We need to select Eclipse
for Java developers from the multitudes of flavors in which it is available. At the time
of writing, the latest Eclipse build is Luna, as shown in the following screenshot:
Once you have downloaded the relevant IDE, go ahead and install it on your
machine. Now, we are all set to write and compile the Java code. It's time to set
up the Android development environment.
[ 11 ]
Wiring Up
Chapter 1
In the new window that pops up, enter the URL https://dl-ssl.google.com/
android/eclipse/ in the section that says type or select a site and press Enter. We
need to select all available items and proceed with the installation. Once the plugin
is successfully installed, we need to restart Eclipse. After restarting, Eclipse will ask
you for the Android SDK location; you can also set it up by navigating to Window
| Preferences | Android. Once the Android SDK location is set, the SDK Manager
will check our installation to find missing items. It will prompt you to download the
latest Android SDK platform and Android platform tools. Check out the selected
items in the Download dialog box. We need to have the recommended Android
build tools and SDK platform. It is safe to not alter the recommended setting and
allow the downloader of Eclipse to download all the required files. The following
screenshot shows the update in progress:
Wiring Up
Setting up GWT
From within Eclipse, launch the Install New Software... window, input the
following link, and install the GWT plugin:
https://dl.google.com/eclipse/plugin/4.4
The last part of the link is actually the Eclipse version and the preceding link is for
Version 4.4.x. Select the checkboxes to install Google Plugin for Eclipse, Google
App Engine SDK, and Google Web Toolkit SDK. Once the plugin is installed,
we need to restart Eclipse.
[ 14 ]
Chapter 1
Gradle also has a build system that helps with building and packaging your
application, without being tied to a specific IDE. This is especially useful if you use
a build or continuous integration server, where IDEs aren't readily available. Instead,
the build server can call the build system, providing it with a build configuration so
it knows how to build your application for different platforms. More information can
be found at http://www.gradle.org/.
At this point, we are very comfortable adding new plugins to Eclipse. Fire up
the new software window to add the Gradle plugin from the link http://dist.
springsource.com/release/TOOLS/gradle. After installation, restart Eclipse
and that's the end of our setup.
[ 15 ]
Wiring Up
The setup application has to be stored for easy access, as we will need it when
we create new LibGDX projects. The purpose of the application is to create all
platform-specific Eclipse projects, such as desktop, Android, iOS, and JavaScript
applications. It also links with all the necessary dependency libraries and the latest
version of LibGDX. The following screenshot shows the Gradle project structure
that clearly explains how the different projects are created under the relevant folders:
[ 16 ]
Chapter 1
[ 17 ]
Wiring Up
We need to specify a name for our project, which is Hello World in this case. Then, we
need to specify a package name for our project. In my case, I am using my company's
package name but you can use any unique package name. It's time to specify our main
class name; take care that there are no spaces in between. While setting the destination
project, make a new folder within your Eclipse Workspace folder so that there are
no possible conflicts between Gradle files and Eclipse workspace metadata files. In
this case, I have specified FirstGradleProject. Link the Android SDK and select
the version of LibGDX that you will use.
In the Sub Projects section, we need to select the platforms that we want the
project to target. Note that we will need a Mac to compile an iOS build.
The Extensions section will link any of the standard LibGDX libraries or packages
available. It is always safe to select the options in this stage rather than hacking
into the project later on. For our Hello World app, we do not need any of these
extensions. Hit the Generate button and your LibGDX Gradle project structure
will be created.
Alternatively, we can create an Eclipse-specific project structure by clicking on
the Advanced button, enabling the Eclipse checkbox, and clicking on Save. If the
project is created this way, then we need to import it as a normal Eclipse project
by navigating to File | Import | General | Existing Projects to Workspace.
This process will need an active Internet connection to load the files needed by
the setup application.
[ 18 ]
Chapter 1
[ 19 ]
Wiring Up
Go ahead and select all the projects and click on Finish to load them to Eclipse.
At this point Gradle will load all the dependencies as per our selection in the
setup application. This is where Gradle will actually load the LibGDX packages
and extensions. The following screenshot shows the process:
[ 20 ]
Chapter 1
In order to run the desktop project, right-click on the Hello World desktop project,
select Run As, and click on Java Application. A popup may ask you to select the
application class and you should select DesktopLauncher to run the app. The
following window will pop up, which means we have successfully created and
run our first Gradle-based LibGDX application:
[ 21 ]
Wiring Up
Running the application on your Android device is also very easy. Connect your
Android device to the development PC via USB and make sure USB debugging
is enabled in the device's settings.
USB debugging can be enabled by navigating to Settings |
Developer options | USB debugging.
In order to see the connected device from within Eclipse, you need to enable the
Devices view. In Eclipse, go to Window | Show View | Other. Then, select Devices
from the Android section. A new tab showing the connected device will be added
to Eclipse. For Windows, we need to install the respective drivers for the connected
phone to show up, but on Mac the connected device would be automatically detected.
Once you see your device listed in the Devices view, right-click on the Hello
World-android project, select Run as, and click on Android Application. Eclipse
will prompt you to select how to launch the Android app. You can select to launch
on a device or on a Android Virtual Device (AVD) if you have set one up already.
Select to launch the application on the device and then the application should show
up on your Android device. Eclipse will show the LogCat view, which shows the
application status:
In order to run the iOS project, you need to be on a Mac and should have Xcode
Version 5 or above installed. Xcode can be downloaded free from the Mac App
Store. It provides the necessary frameworks and the iOS Simulator tool. Right-click
the Hello World-ios project, select Run As, and select iOS Simulator App.
You can select either of the simulator options, iPad or iPhone. This will start the
RoboVM cross compilation and would take some time for entire classes to be
compiled. Eventually, you will see the app running on the iOS Simulator.
[ 22 ]
Chapter 1
Getting the HTML project to run is the trickiest part of them all. We need to follow
exactly what the LibGDX wiki tell us to do. Right-click on the Hello World-html
project, select Run As, and click on External Tools Configuration. Create a new
configuration by double-clicking the Program entry in the left sidebar. Give the
configuration a name, for example, GWT SuperDev. Set the location field to the
gradlew.bat (Windows) or gradlew (Linux, Mac) file. Set the working directory
to the root folder of your project and specify html:superDev as the argument.
Click on Apply and then click on Run.
Wait until you see the message The code server is ready in the console view.
After that, go to the URL http://localhost:8080/html. You can leave the server
running. If you change the code, simply click on the SuperDev Refresh button in
the browser. This will recompile your app and reload the site.
Check out this screenshot to see the app running on a browser:
[ 23 ]
Wiring Up
The SpriteBatch class is a class that facilitates the efficient drawing of images
on the screen. The create function, which will be called when the application is
launched, just creates a new SpriteBatch class and a Texture class named img
that loads a texture from the external asset badlogic.jpg. The render function
is called continuously and can be considered as our game loop. It clears the screen
and draws the texture onto screen at the coordinates (0,0). This means the origin
of the coordinate system in LibGDX is the bottom-left corner of the screen, as we
can see that the image is placed there. We will revisit the graphics package in the
next chapter.
The following code clears the screen before each draw call:
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
The next bit of code starts the batch drawing, draws the texture at the specified
coordinates, and closes the batch drawing:
batch.begin();
batch.draw(img, 0, 0);
batch.end();
[ 24 ]
Chapter 1
The only thing missing is the external image file, as we won't be able to find it
among the core project files. LibGDX follows the convention to store all asset files
within the assets folder in the Android project. Hence, we can find badlogic.jpg
within the assets folder in the Hello World-android project. The assets folder
is shared among all the other projects. All the other projects are simple wrapper
projects that have platform-specific code and data that will launch the code in the
core project. You can easily explore the projects on your own, but we will revisit
specific platforms in the final chapter.
Now, let's edit the code in HelloWorld.java in the core project to remove the
texture drawing and to add our text display. The code is as follows:
public class HelloWorld extends ApplicationAdapter
{
SpriteBatch batch;
BitmapFont font;
@Override
public void create ()
{
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("verdana39.fnt"),
Gdx.files.internal("verdana39.png"), false);
font.setColor(Color.RED);
}
@Override
[ 25 ]
Wiring Up
public void render ()
{
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Hello World", 200, 200);
batch.end();
}
@Override
public void dispose()
{
batch.dispose();
font.dispose();
}
}
The BitmapFont class requires the .fnt and .png file to create the font. In the
render function, we draw the Hello World text at the coordinates (200,200). I have
also added an overridden dispose function that releases the memory by destroying
the created instances. Congratulations! You have our shining Hello World text.
This method may not always be suitable to display text, as we may need to show
text in multiple sizes. In such cases, we will use the Freetype extension that enables
us to use a ttf font to create bitmap fonts of different sizes dynamically at runtime.
We will revisit fonts in detail in Chapter 4, Bring in the Extras!
Running demos
For the adventurous among you, this is the chance to dive deeper into LibGDX
by checking out the fully functional game demos. You can find the links for these
games at https://github.com/libgdx/libgdx/wiki/Running-Demos. The
most interesting one is the example project similar to Flappy Bird, The plane that
couldn't fly good. The link to this project is https://github.com/badlogic/
theplanethatcouldntflygood. In order to explore this project, we need to clone
the repository in Git or download it on our PC. Once downloaded, we can import
it to Eclipse as a Gradle project.
[ 26 ]
Chapter 1
This is a very simple project to get you started and can be used as a starter code for
your Flappy Bird game. The whole code is in the single file PlaneGame.java in the
core project.
Running tests
The LibGDX tests project is a treasure trove of goodies. There are numerous small tests
exploring the different features of LibGDX. These tests are the ideal way to get started
with LibGDX and they also let you learn new things in an easy way. Alternatively,
they act as a source of functional sample code that we can simply copy and paste for
our own use cases. The LibGDX wiki entry for running these tests advises us to use
Ant to set up these tests on our PC. The link is https://github.com/libgdx/libgdx/
wiki/Running-Tests. The tests can be found at https://github.com/libgdx/
libgdx/tree/master/tests/gdx-tests/src/com/badlogic/gdx/tests.
You can temporarily set up Ant after downloading it from http://ant.apache.
org/bindownload.cgi. Assuming that it is extracted to /Setups/apacheant-1.9.4, we can temporarily install ANT using the terminal on a Mac. In the
terminal, enter the following code:
export ANT_HOME=/Setups/apache-ant-1.9.4
export PATH=${PATH}:${ANT_HOME}/bin
In the terminal, navigate to the folder where LibGDX Git project is cloned. Run the
Ant command to fetch dependencies:
ant -f fetch.xml
[ 27 ]
Wiring Up
This will download all the LibGDX dependencies for all the projects. Later, we can
import all these projects into Eclipse by navigating to Import | Existing Projects
into Workspace. After importing the Demo and Tests projects, our Package Explorer
in Eclipse will look something like this:
[ 28 ]
Chapter 1
The test examples are contained in the gdx-tests project. This project only contains
the source code. To actually start the tests on the desktop, you have to run the
LwjglTestStarter class contained in the gdx-tests-lwjgl project. To run the
tests on Android, simply fire up the gdx-tests-android project in the emulator or
on a connected device! To run the tests in your browser, fire up the gdx-tests-gwt
project. For iOS, you can start the gdx-tests-robovm project. Play with them.
[ 29 ]
Wiring Up
Summary
This chapter explained a lot of theory that lays the solid foundation for all our
development. This chapter will serve as a reference to set up your development
environment if you move to a new workplace or get a new laptop. You learned
to set up Eclipse-based Android and Java development environments. We used
the gdx-setup tool to create a Gradle-based LibGDX project, which was successfully
imported to Eclipse with the help of associated support plugins. We explored the
project structure of a typical LibGDX cross-platform project.
We successfully executed the Hello World project on desktop, Android, iOS,
and the browser. Some minor editing of the code helped us display the text Hello
World using the BitmapFont class. It is very important to successfully import the
LibGDX Demo and Tests and we used Ant to get them running.
In the next chapter, we will start with the graphics package in LibGDX and get
started with our game.
[ 30 ]
www.PacktPub.com
Stay Connected: