Home Game Development Learning Libgdx Game Development

Learning Libgdx Game Development

books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to Libgdx and Project Setup
About this book
Game development is a field of interdisciplinary skills, which also makes it a very complex topic in many respects. One decision that usually needs to be made at the beginning of a game development processis to define the kind of computer system or platform the game will be developed for. This does not pose any problems in general but as soon as the game should also be able to run on multiple platforms it will become a developer's nightmare to maintain several distinct copies of the same game. This is where the libGDX multi-platform game development framework comes to the rescue! "Learning Libgdx Game Development" is a practical, hands-on guide that provides you with all the information you need to know about the libGDX framework as well as game development in general so you can start developing your own games for multiple platforms. You will gradually acquire deeper knowledge of both, libGDX and game development while you work through twelve easy-to-follow chapters. "Learning Libgdx Game Development" will walk you through a complete game development cycle by creating an example game that is extended with new features over several chapters. These chapters handle specific topics such as organizing resources, managing game scenes and transitions, actors, a menu system, using an advanced physics engine and many more. The chapters are filled with screenshots and/or diagrams to facilitate comprehension. "Learning Libgdx Game Development" is the book for you if you want to learn how to write your game code once and run it on a multitude of platforms using libGDX.
Publication date:
September 2013
Publisher
Packt
Pages
388
ISBN
9781782166047

 

Chapter 1. Introduction to Libgdx and Project Setup

This book will take you on an exciting tour to show and teach you about game development using the open source Libgdx framework. Actually, you have chosen just the right time to read about game development as the game industry is in a remarkable state of change. With the advent of increasingly powerful smartphones and tablets as well as the ever-growing application stores for desktop computers and mobile platforms serving millions of users a day, it has never been easier for Independent Game Developers (also known as Indies) to enter the market with virtually no risks and very low budgets.

In this chapter you will learn about what Libgdx is and what the advantages are to use it for developing your own games. You will also get a brief overview of the feature set that Libgdx provides.

Before you can start developing games with Libgdx, you have to install and set up your development environment accordingly. You will be using the freely available and open source software Eclipse as your Integrated Development Environment (IDE ) and set up a basic project that uses Libgdx. It will feature a runnable example application for each currently supported target platform. These platforms are as follows:

  • Windows

  • Linux

  • Mac OS X

  • Android (Version 1.5 and above)

  • HTML5 (Using JavaScript and WebGL)

Note

The target platforms Windows, Linux, and Mac OS X will from now on be referred to as Desktop and also share a project in our development environment.

An alert reader may have noticed that iOS is missing in the list of supported target platforms. Fortunately, it is very likely that Libgdx will support the iOS platform soon as the developers have already put great effort into this feature. At the time of writing of this book, it is said that iOS, starting from Version 5.0 and above, will be supported.

Furthermore, you are going to explore what a game needs by looking at it from a technical standpoint, and why it is so important to plan a game project before the development starts.

At the end of this chapter, you will be introduced to the game project that is going to be developed and enhanced throughout this book.

 

Diving into Libgdx


Libgdx is an open source, cross-platform development framework, which is designed mainly, but not exclusively, to create games using the Java programming language. Besides Java, Libgdx also makes heavy use of the C programming language for performance-critical tasks, to incorporate other C-based libraries and to enable cross-platform capabilities. Moreover, the framework abstracts the complex nature of all its supported target platforms by combining them into one common Application Programming Interface (API). One of the highlights of Libgdx is the ability to run and debug your code on the desktop as a native application. This enables you to use very comfortable functions of the Java Virtual Machine (JVM), such as Code Hot Swapping, which in turn lets you immediately see the effect of your changed code at runtime. Therefore, it will significantly reduce your time to iterate through different ideas or even to find and fix nasty bugs more quickly.

Another critical point is to understand that Libgdx is a framework and not a game engine that usually comes with lots of tools, such as a full-blown level editor and a completely predefined workflow. This might sound like a disadvantage at first but actually it turns out to be an advantage that enables you to freely define your own workflow for each project. For example, Libgdx allows you to go low-level so you could add your own OpenGL calls if that really became necessary at some point. However, most of the time it should be sufficient enough to stay high-level and use the already built-in functionalities of Libgdx to realize your ideas.

 

Features of Libgdx 0.97


Since the release of Libgdx Version 0.1 back in March 2010, a lot of work has been contributed in order to improve this library. The latest stable release of Libgdx is version 0.97 from November 2012, which we are going to use throughout this book.

Here is the list of features taken from the official website (http://libgdx.badlogicgames.com/features.html):

Graphics

  • Rendering through OpenGL ES 1.x and 2.0 on all platforms

  • Custom OpenGL ES 2.0 bindings for Android 2.0 and above

  • Low-level OpenGL helpers:

    • Vertex arrays and vertex buffer objects

    • Meshes

    • Textures

    • Framebuffer objects (GLES 2.0 only)

    • Shaders, integrating easily with meshes

    • Immediate mode rendering emulation

    • Simple shape rendering

    • Automatic software or hardware mipmap generation

    • ETC1 support (not available in JavaScript backend)

    • Automatic handling of OpenGL ES context loss that restores all textures, shaders, and other OpenGL resources

  • High-level 2D APIs:

    • Custom CPU side bitmap manipulation library

    • Orthographic camera

    • High-performance sprite batching and caching, and handling OpenGL ES 1.x and 2.0 differences transparently

    • Texture atlases with whitespace stripping support, which are either generated offline or online

    • Bitmap fonts (does not support complex scripts like Arabic or Chinese), which are either generated offline or loaded from TTF files (unsupported in JavaScript backend)

    • 2D Particle system

    • TMX tile map support

    • 2D scene-graph API

    • 2D UI library, based on scene-graph API, and fully skinable

  • High-level 3D APIs:

    • Perspective camera

    • Decal batching for 3D billboards or particle systems

    • Basic loaders for Wavefront OBJ and MD5

    • Work in progress: MD2, Ogre XML and FBX support, and 3D rendering API with materials and lighting system

Audio

  • Streaming music and sound effect playback for WAV, MP3, and OGG

  • Direct access to audio device for PCM sample playback and recording (unsupported in JavaScript backend)

  • Decoders for OGG and MPG3 formats (unsupported in JavaScript backend)

  • Pitch shifting, time stretching, and playback rate modification (unsupported in JavaScript backend)

Input Handling

  • Using abstractions for mouse and touchscreen, keyboard, accelerometer, and compass.

  • Gesture detector: detects taps, panning, flinging, and pinch zooming.

  • Gdx remote: to control your desktop application via your Android phone. Useful to test multi-touch gestures while debugging your desktop application.

File I/O

  • Filesystem abstraction for all platforms

  • Read-only filesystem emulation for JavaScript backend

  • Binary file support for JavaScript backend

  • Preferences for lightweight setting storage

Math and Physics

  • Matrix, vector, and quaternion classes. Matrix and vector operations are accelerated via native C code where possible.

  • Bounding shapes and volumes.

  • Frustum class, for picking and culling.

  • Catmull-Rom splines.

  • Common interpolators.

  • Concave polygon triangulation.

  • Intersection and overlap testing.

  • JNI wrapper for Box2D physics. It is so awesome that other engines use it as well.

  • Experimental JNI Wrapper for bullet physics.

Utilities

  • Custom collections with primitive support

  • JSON writer and reader with POJO (de-)serialization support

  • XML writer and reader

Tools

  • Gdx Setup UI for easy project setup

  • Particle editor

  • Texture packer

  • Bitmap font generator

 

Getting in touch with the community


The Libgdx project enjoys a steadily growing and active community. If you ever find yourself being stuck with a problem and you just cannot figure out how to solve it, check out the official forum at http://badlogicgames.com/forum/. There is a great chance someone else has already asked your question and has even found a solution with the help of the community. Otherwise, do not hesitate to ask your question on the forums.

There is also an official IRC channel (#libgdx) on Freenode (irc.freenode.net) where you can find some of the users and developers to talk about Libgdx.

If you want to read about the latest news in development of Libgdx, visit the blog of Mario Zechner who is the founder of the Libgdx project or follow him on Twitter.

Libgdx website: http://libgdx.badlogicgames.com/

Blog: http://www.badlogicgames.com/

Twitter: http://www.twitter.com/badlogicgames/

Also check out the following links for more in-depth information:

Wiki: http://code.google.com/p/libgdx/wiki/TableOfContents

API overview: http://libgdx.badlogicgames.com/nightlies/docs/api/

 

Prerequisites for installing and configuring


Before you can start writing any application or game with Libgdx, you need to download and install the library and also some additional software.

Java Development Kit (JDK)

Due to the fact that Libgdx is a framework based on Java, it is necessary to download the JDK. The software is freely available on Oracle's website at http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Click on the DOWNLOAD button to start downloading the latest JDK.

Note

It is important to choose the JDK instead of the JRE package. The reason is that the JDK package contains both, the Java Runtime Environment (JRE ) to run java applications and everything else that is required to develop them.

You will have to accept the license agreement and choose the version that is appropriate for your platform. For example, if you are using a 64-bit version of Windows, choose the download labeled as Windows x64.

To install the JDK, simply run the downloaded installer file (for example, jdk-7u11-windows-x64.exe) and follow the instructions on the screen.

In the welcome screen of the installer, click on Next > to continue.

Then, keep all features selected as to be installed and click on Next > again to continue.

Once the installation has been completed, click on the Close button to exit the installer.

Eclipse – Integrated Development Environment (IDE)

The next step is to download and install Eclipse, a freely available and open source IDE for developing applications in Java. Go to http://www.eclipse.org/downloads/ and choose Eclipse IDE for Java Developers to download for the platform you are using.

Once the download has finished, extract the archive to C:\eclipse\.

Downloading Libgdx

Next, go to http://code.google.com/p/libgdx/downloads/list and choose the file libgdx-0.9.7.zip to download Libgdx.

Note

At the time of writing this book, the latest stable version of Libgdx is 0.9.7. It is recommended to use the same version while working with this book.

In the meanwhile, create a new folder in the root folder of your C drive with the name libgdx. Once the download has finished, move the archive to C:\libgdx\. Then, open the archive and extract the .jar-File gdx-setup-ui to C:\libgdx\. The extracted program will help you later with creating new game projects in an easy to use GUI.

Installing Android SDK

The Android mobile OS is one of Libgdx's supported target platforms. Before you can create Android applications, you have to download and install the Android SDK. Go to http://developer.android.com/sdk/index.html and click on the Download the SDK Tools for Windows button. Should you be using an OS other than Windows, you will have to scroll down a bit further, click on Download for other platforms and choose the appropriate platform.

Once the download has finished, run the installer (for example, installer_r22.0.4-windows.exe) and follow the instructions on the screen.

You may see the following screen when you try to install the Android SDK. The installer cannot find the JDK although you have already installed it.

You need to set the value of the environment variable JAVA_HOME to the installation path of the JDK. To find the correct path go to C:\Program Files\Java\. You should see a folder starting with jdk in its name. Take the full name of this folder (here, jdk1.7.0_11) and append it to its path.

The complete path should now look similar to this: C:\Program Files\Java\jdk1.7.0_11.

Now you have to set the environment variable. Click on the Windows Start button and right-click on Computer. Then click on Properties to open the control panel system window.

Click on Advanced system settings on the left side of the window.

The System Properties window will appear. Next, click on the Environment Variables … button.

The Environment Variables window will appear. Click on the upper New … button that corresponds to User variables for <USERNAME>. A window with the title New User Variable will appear.

Now, fill in the two text fields. Use JAVA_HOME in the Variable name: field and the JDK's path you found out earlier in the Variable value: field.

Great! Now your system is prepared for the Android SDK installer. Please make sure to exit the Android SDK installer in case it is still running to let the change take effect. You should be presented with the following screen after the installer has restarted.

Now, back in the Android SDK setup, click on Next > to continue the installation.

The following screen will ask you to choose the users for which the Android SDK should be installed. Usually, the suggested selection Install just for me is perfectly fine, so just click on Next > to continue.

Now, choose the installation location on your computer. You can safely keep the suggested location and click on Next > to continue.

After that, you will be asked to choose a start menu folder. Again, you can safely keep the suggestion and click on Install to start the installation process.

After the installation is complete, click on Next > to continue.

Once the installation has finished, you can choose to start the Android SDK Manager. Leave the checkbox Start SDK Manager (to download system images, etc.) enabled and click on Finish to start the manager.

The Android SDK Manager enables you to download system images for the specific API levels you want to be able to develop applications for. For up-to-date and detailed information about Android API levels, check out the following link at http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels.

Now, choose at least Android 2.2 (API 8) and/or any other higher API levels you may need and click on the Install packages … button to automatically download and install all relevant files. The reason why we want to use at least API level 8 is that earlier versions before Android 2.2 do not support OpenGL ES 2.0, which we will need in later chapters. Using a certain API level also allows you to control the range of devices that will be able to see and install on your application via the Google Play Store.

Once the download and installation process has finished, close the Android SDK Manager window.

Running Eclipse and installing plugins

Great! You are almost done setting everything up. The remaining steps involve running Eclipse for the first time and installing two important plugins, which are required to develop applications for Android and HTML5/GWT with Eclipse.

Open Windows Explorer and go to the location where you extracted Eclipse (here, C:\eclipse\) and simply run the program by double-clicking on the executable called eclipse.

Eclipse will ask you to select a so-called workspace. This is the folder where all your projects will be saved in. We want to use the folder C:\libgdx\ we created a bit earlier.

Select the Use this as the default and do not ask again checkbox, if you do not want to see this dialog every time you start Eclipse. To proceed, confirm the dialog by clicking on the OK button.

The first time Eclipse is started with a new workspace, it will greet you with a welcome screen. Simply click on the small cross (x) of the Welcome tab to close it.

You should see the standard view of Eclipse now, which is also called the Java Perspective . On the left-hand side you can see the Package Explorer section. This is where you will see and manage your different projects. That is all you need to know about Eclipse for the moment.

In case you have never worked with Eclipse before, it may seem quite overwhelming with all these windows, toolbars, huge context menus, and so on. However, rest assured that all steps will be discussed in detail as required to make it easy for you to follow.

To install new plugins, go to the menu bar and click on Help, and then Install New Software…. This will open the Install window where you can type special repository URLs to browse for new plugins. Google provides a list with such URLs at https://developers.google.com/eclipse/docs/getting_started. You have to choose the correct URL that corresponds with your Eclipse installation.

At the time of writing this book, Eclipse 4.2.1 (Juno) was the most current version available. According to Google's website, their suggested URL for our version is http://dl.google.com/eclipse/plugin/4.2.

Type the URL into the text field that is labeled Work with: and press return to let Eclipse request a list of available downloads. Select everything in the list that is shown in Developer Tools to add support for Android applications. Then, select everything in Google Plugin for Eclipse (required) to install the required Eclipse plugin. Lastly, select Google Web Toolkit SDK 2.5.1 in SDKs to add support for HTML5/GWT applications and click on Next > to continue.

Now, click on Next > to start the installation.

You will now be prompted to accept the terms of the license agreements by selecting the option I accept the terms of the license agreements. You have to do this before you can click on Finish to continue, as shown in the following screenshot:

The download process should only take a couple of minutes, depending on the speed of your network connection. When downloading has finished, Eclipse will show a security warning that you are about to install unsigned content and wants to know whether it should continue or abort. There is always a potential risk of installing malicious software. However, in this case the download is provided by Google, a well-known company, which should be trustworthy enough. Click on the OK button to accept the warning and continue the installation, as shown in the following screenshot:

After the installation has finished, a final restart of Eclipse is required. Click on the Yes button to confirm the restart, as shown in the following screenshot:

Congratulations! You have just finished the installation of everything you will need to develop and build your own games with Libgdx.

 

Creating a new application


The next step is to create a new application. Usually, you would have to create several projects in Eclipse: one project for the shared game code, another one for the desktop launcher, and two more for the Android and HTML5/GWT launchers. Furthermore, the projects would also have to be configured and linked together in a certain way. This is quite a time-consuming and more or less an error-prone process for inexperienced users.

Luckily, Libgdx comes with a nice tool called Libgdx Project Setup, which can do all of the things described previously. It is able to generate preconfigured projects for a new application, which can be directly imported into Eclipse.

To run the tool, open the Windows Explorer, go to C:\libgdx\, and double-click on the gdx-setup-ui file. When the program starts, click on the big Create button as shown in the following screenshot:

In the next window, you will see a box called CONFIGURATION on the left-hand side. Here you can configure what the tool will generate.

Enter demo in the Name field, which defines a common project name for your application. Each launcher project will add its own suffix to it, such as -desktop, -android, or -html. A preview of the outcome is shown in the OVERVIEW box on the right-hand side.

The Package field defines the name of your Java package. This needs to be a unique identifier written in lowercase, which is usually derived from a reversed domain name. You do not have to own a domain name nor does it have to really exist, but it helps in choosing non-conflicting namespaces for Java applications. This is especially important on Android, as identical package names for two separate applications would mean that the already installed application is going to be overwritten by the second one while trying to install it. For this demo application, use com.packtpub.libgdx.demo as the package name for now.

The Game class field defines the name of the main class in the shared game code project. Enter MyDemo as the game class name.

The Destination field defines the destination folder where all the projects will be generated. Click on the blue folder button and set the destination folder to C:\libgdx\.

In another box called LIBRARY SELECTION, the status of required libraries is shown. If there is any item listed in red color, it needs to be fixed before any project can be generated. You should see LibGDX being listed in red in the Required section. Click on the blue folder icon next to it as shown in the following screenshot:

Then, choose the downloaded archive file libgdx-0.9.7.zip from C:\libgdx\ and click on Open, as shown in the following screenshot:

The text color of the LibGDX label should have changed from red to green by now. Click on the Open the generation screen button to continue as shown in the following screenshot:

Click on the Launch! button to generate all projects as shown in the following screenshot:

All done! You can now go to Eclipse and start importing the generated projects into your workspace. To do this, simply navigate to File | Import, as shown in the following screenshot:

In the Import dialog, open the General category, select Existing Projects into Workspace, and click on the Next > button as shown in the following screenshot:

Click on the radio button Select root directory and enter C:\libgdx into the text field. This is the directory where all your generated projects were created. You need to confirm your text input by pressing the return key once. Eclipse will start to scan the directory for projects and list them. Leave all checkboxes selected and click on the Finish button, as shown in the following screenshot:

Eclipse will automatically try to build (compile) all four newly imported projects in your workspace and probably fail. There are two issues that need to be resolved manually after the import. The first one is reported directly to the Console window in Eclipse. It complains about being unable to resolve the target android-15.

You have to open the project properties of the demo-android project. First, select it in the Package Explorer box on the left-hand side. Then go to the menu bar and navigate to Project | Properties , as shown in the following screenshot:

The title of the window should say Properties for demo-android. If this is not the case, close the window and make sure you have selected the correct project and try again. Next, select Android from the list on the left-hand side. You will see a list of targets that are available on your system. Select Android 2.2, which uses API Level 8, and click on the OK Button.

Eclipse should recognize the change and successfully build the Android project this time.

The second issue requires you to click on the Problems tab in Eclipse. Open the Errors list and right-click on the reported problem, which should say The GWT SDK JAR gwt-servlet.jar is missing in the WEB-INF/lib directory. Choose Quick Fix from the context menu as shown in the following screenshot:

In the Quick Fix dialog, select Synchronize <WAR>/WEB-INF/lib with SDK libraries as the desired fix and click on the Finish button, as shown in the following screenshot:

The two issues should be solved by now, which means all projects now are automatically built without failure and can be compiled.

 

Kicking your game to life


Let us take a moment to discuss what a game basically consists of. From a very high level point of view, a game can be split up into two parts: game assets and game logic.

Game assets include everything that is going to be used as a kind of working material in your game, such as images, sound effects, background music, and level data.

Game logic is responsible for keeping track of the current game state and to only allow a defined set of state transitions. These states will change a lot over time due to the events triggered either by the player or by the game logic itself. For example, when a player presses a button, picks up an item, or an enemy hits the player, the game logic will decide for the appropriate action to be taken. All this is better known as game play. It constrains the ways of action in which a player can interact with the game world, and also how the game world would react to the player's actions.

To give you a better idea of this, take a look at the following diagram:

The very first step is to initialize the game, that is, loading assets into memory, creating the initial state of the game world, and registering with a couple of subsystems such as input handlers for keyboard, mouse and touch input, audio for playback and recording, sensors, and network communication.

When everything is up and running, the game logic is ready to take over and will loop for the rest of the time until the game ends and will then be terminated. This kind of looping is also referred to as the game loop. Inside the game loop, the game logic accumulates all (new) data it is interested in and updates the game world model accordingly.

It is very important to consider the speed at which updates will occur in the game world. Currently, the game would just run at the maximum speed of the available hardware. In most cases this is not a desirable effect because it makes your game dependent on the processing power and the complexity of the scene to be rendered, which will vary from computer to computer. This implies that your game world will also progress at different speeds on different computers with an almost always negative impact on the game play.

The key to tackle this issue is to use delta times to calculate the fractional progress of the game world. Now every update to the game world will occur in relation to real time that has passed since the last frame was rendered. You will see how this actually works with Libgdx in later examples.

What you have just read was an overview of the basic concept for creating games. Yes, it is that simple! Frankly speaking, there is a lot more to learn before your application becomes a real game. There are lots of topics and concepts waiting to be discovered in this book. For instance, you will need to understand how to use and manage different images in an efficient manner. Efficiency becomes even more important if you plan to target mobile devices such as Android smartphones, where available resources are constantly scarce.

 

Key to success lies in planning


Great! Now you have a basic understanding of what a game is and may need. It appears to be a good idea to dedicate some additional time to think about your first game project and create a plan for it. In general, planning your game projects is what you should always do in the first place before any actual work is done. For novice game developers it might be very tempting to skip this planning phase, which admittedly is a lot more fun in the beginning, but this approach is very likely to fall short in the long run. You will need some sort of outline of what you want to achieve. It does not have to be a very long and detailed description.

A simple and brief feature list of your design goals will do just fine for this purpose. The reason behind this is that you will make yourself aware of each single feature that is part of your game. In addition, this list will also serve you as a great tool to measure and compare your progress in the game during the development phase. Please bear in mind that game development is a very dynamic and iterative process. Although you should try to adhere to your list of design goals for most of the time, there should always be room to adapt to shifting requirements. Just keep in mind that adhering to the list will make sure that you are going to push development in the right direction. Conversely, it will let you focus on the important parts first, while also protecting you from running out of time and taking too many detours that prevent you from reaching the finish line due to unclear goals.

 

Game project – Canyon Bunny


To make this guide both easy and fun to read, it makes perfect sense to show how to plan and develop a whole game project throughout this book. As we now know, planning should be the first step to take on the journey of any new game project.

So, let us begin with the outline:

Note

Name or Working Title: Canyon Bunny

Genre: 2D Side-Scrolling Jump and Run

List of actors:

  • Player character (can jump and move forward; controlled by player)

  • Rocks, serving as platforms for the player character and items

  • Canyons in the background (level decoration)

  • Clouds in the sky (level decoration)

  • Water at the bottom of the level (deadly for player character)

  • Collectible items for the player: gold coins, feather power-up

Next, it is always helpful to write down some supporting text to further describe the overall behavior of the game and how features should be implemented.

Description of the game

The game world is presented in 2D side view to the player. The view is scrolling horizontally to the right when the player character moves forward. The background shows distant canyons and clouds in the sky. The bottom of the level is filled with water and will instantly kill the player character if both get into contact with each other.

The player character will move on and jump over to random rocks, sticking out of the water. The width and height will be different to make the game more challenging. The player is only in control of a jump button, which will keep the automatically forward-moving player character from falling down into the deadly water.

The level will be randomly populated with collectible items consisting of gold coins and feather power-ups. Collecting the gold coins will increase the player's high score. The feather power-up grants the player character the ability to fly for a limited time and can be used by repeatedly pressing the jump button. The player's goal is to beat the last high score.

Since a picture is worth a thousand words, creating a sketch based on our outline can help us even more to get a better idea of the resulting game. Moreover, changing a sketch is usually a lot easier than having to change (complex) game code. So you really want to keep it very simple like just grabbing your pen and paper and starting to draw. If you feel lucky or have some time to spend, you can do something more elaborate, of course.

Here is a sketch for Canyon Bunny:

The previous sketch has been created entirely by using vector graphics. Using vector graphics in favor of raster graphics for your sketches can be an advantage as they are infinitely scalable to any size without losing image quality. However, the final graphics used in games are almost, always, rasterized graphics, simply because vector graphics are costly to render in real time. So, the common approach is to create vector graphics and later on export them choosing an appropriate rasterized graphics file format, such as .png (Portable Network Graphics) for lossless compression with alpha channel support, or .jpg (JPEG) for lossy but high compression without alpha channel support.

For more details, check out the following Wikipedia articles:

There is a free and open source tool called Inkscape. It allows you to easily create your own drawings as vector graphics, and is available for Windows, Linux, and Mac OS X. Check out the project's website at http://inkscape.org/.

 

Summary


We learned a lot in this chapter about Libgdx and all the other bits and bobs to prepare your system for multi-platform game development, specifically on the following points:

  • We discussed every step in great detail to successfully download, install, and configure all required software components: JDK, Eclipse, Libgdx, Android SDK, and two additional Eclipse plugins for Android and HTML5/GWT

  • We learned how to use the project setup tool that comes with Libgdx to easily generate all required Eclipse projects for a new application, and how to import them into Eclipse including minor troubleshooting

  • We also learned what a game needs to come alive

  • We found out why planning game projects is so important

  • We have seen how to plan a game project by writing an outline

In Chapter 2, Cross-platform Development – Build Once, Deploy Anywhere, you will learn more about how to deploy and run a Libgdx application on all supported target platforms. Building on this knowledge, we will finally jump to the first code examples where the magic happens and take a closer look at it to find out how it works.

Learning Libgdx Game Development
Unlock this book and the full library FREE for 7 days
Start now