Learning Libgdx Game Development - Andreas Oehlke - E-Book

Learning Libgdx Game Development E-Book

Andreas Oehlke

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 402

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Libgdx Game Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introduction to Libgdx and Project Setup
Diving into Libgdx
Features of Libgdx 0.97
Graphics
Audio
Input Handling
File I/O
Math and Physics
Utilities
Tools
Getting in touch with the community
Prerequisites for installing and configuring
Java Development Kit (JDK)
Eclipse – Integrated Development Environment (IDE)
Downloading Libgdx
Installing Android SDK
Running Eclipse and installing plugins
Creating a new application
Kicking your game to life
Key to success lies in planning
Game project – Canyon Bunny
Description of the game
Summary
2. Cross-platform Development – Build Once, Deploy Anywhere
The demo application – how the projects work together
Backends
LWJGL (Lightweight Java Game Library)
Android
WebGL
Modules
The application module
Logging
Shutting down gracefully
Persisting data
Querying the Android API Level
Querying the platform type
Querying memory usage
Graphics module
Querying delta time
Querying display size
Querying the FPS (frames per second) counter
Audio module
Sound playback
Music streaming
Input module
Reading the keyboard/touch/mouse input
Reading the accelerometer
Starting and canceling vibrator
Catching Android soft keys
The files module
Getting an internal file handle
Getting an external file handle
The network module
HTTP GET and HTTP POST
Client/server sockets
Opening a URI in a web browser
Libgdx's Application Life-Cycle and Interface
Starter Classes
Running the demo application on a desktop
Running the demo application on Android
Running the demo application in a WebGL-capable web browser
The demo application – time for code
Inspecting an example code of the demo application
The create() method
The render() method
The dispose() method
Having fun with the debugger and Code Hot Swapping
Summary
3. Configuring the Game
Setting up the Canyon Bunny project
Using a class diagram for Canyon Bunny
Laying foundations
Implementing Constants
Implementing CanyonBunnyMain
Implementing WorldController
Implementing WorldRenderer
Putting it all together
Building the game loop
Adding test sprites
Adding game world's debug controls
Adding CameraHelper
Adding camera debug controls using CameraHelper
Summary
4. Gathering Resources
Setting a custom Android application icon
Creating texture atlases
Loading and tracking assets
Organizing assets
Testing assets
Handling level data
Summary
5. Making a Scene
Creating game objects
The rock object
The mountains object
The water overlay object
The clouds object
Implementing the level loader
Assembling the game world
Implementing the game GUI
The GUI score
The GUI extra lives
The GUI FPS counter
Rendering the GUI
Summary
6. Adding the Actors
Implementing the actor game objects
Creating the gold coin object
Creating the feather object
Creating the bunny head object
Updating the rock object
Completing the level loader
Adding the game logic
Adding collision detection
Losing lives, game over, and fixing the camera
Adding the game over text and the feather icon to the GUI
Summary
7. Menus and Options
Managing multiple screens
Exploring Scene2D (UI), TableLayout, and skins
Using Libgdx's scene graph for the menu UI
Building the scene for the menu screen
Adding the background layer
Adding the objects layer
Adding the logos layer
Adding the controls layer
Adding the Options window layer
Building the Options window
Using the game settings
Summary
8. Special Effects
Creating complex effects with particle systems
Adding a dust particle effect to the player character
Moving the clouds
Smoothing with Linear interpolation (Lerp)
Letting the rocks float on the water
Adding parallax scrolling to the mountains in the background
Enhancing the game screen's GUI
Event – player lost a life
Event – score increased
Summary
9. Screen Transitions
Adding the screen transition capability
Implementing transition effects
Knowing about interpolation algorithms
Creating a fade transition effect
Creating a slide transition effect
Creating a slice transition effect
Summary
10. Managing Music and Sound Effects
Playing back music and sound effects
Exploring the Sound interface
Exploring the Music interface
Accessing the audio device directly
Exploring the AudioDevice interface
Exploring the AudioRecorder interface
Using sound generators
About the sfxr generator
About the cfxr generator
About the bfxr generator
Adding music and sounds to Canyon Bunny
Summary
11. Advanced Programming Techniques
Simulating physics with Box2D
Exploring the concepts of Box2D
Understanding rigid bodies
Choosing body types
Using shapes
Using fixtures
Simulating physics in the world
Physics body editor
Preparing Canyon Bunny for raining carrots
Adding the new assets
Adding the carrot game object
Adding the goal game object
Extending the level
Letting it rain carrots
Working with shaders in Libgdx
Creating a monochrome filter shader program
Using the monochrome filter shader program in Canyon Bunny
Adding alternative input controls
Summary
12. Animations
Manipulating actors through actions
Actions for manipulating actors
Controlling the order and time of execution
Animating the menu screen
Animating the gold coins and bunny head actors
Animating the menu buttons and options window
Using sequences of images for animations
Packing animations using the texture packer
Choosing between animation play modes
Animating the game screen
Defining and preparing new animations
Animating the gold coin game object
Animating the bunny head game object
Summary
Index

Learning Libgdx Game Development

Learning Libgdx Game Development

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2013

Production Reference: 1190913

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78216-604-7

www.packtpub.com

Cover Image by Aniket Sawant (<[email protected]>)

Credits

Author

Andreas Oehlke

Reviewers

Ebenezer Edelman

Matthias Markowski

David Saltares Márquez

Chris Moeller

Acquisition Editors

Kartikey Pandey

Julian Ursell

Lead Technical Editor

Mayur Hule

Technical Editors

Menza Mathew

Amit Shetty

Harshad Vairat

Copy Editors

Mradula Hegde

Gladson Monteiro

Sayanee Mukherjee

Kirti Pai

Adithi Shetty

Project Coordinator

Apeksha Chitnis

Proofreaders

Paul Hindle

Mario Cecere

Indexer

Rekha Nair

Graphics

Abhinash Sahu

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Andreas Oehlke is a professional software engineer and a computer scientist who feels very much at home on any Linux/Unix machine. He holds a Bachelor's degree in Computer Science and loves to assemble and disassemble software and hardware alike. An exorbitant affinity for electronics and computers has always been his trademark. His hobbies include game and web development, programming in general (software design and new languages), programming embedded systems with microcontrollers, playing sports, and making music.

He currently works full-time as a software engineer for a German financial institution. Furthermore, he has worked as a consultant and a game developer in San Francisco, CA. In his spare time, he provides his expertise to a German startup called Gamerald (http://www.gamerald.com/).

I want to thank my parents, Michael and Sigrid, and my brother Dennis for their constant and invaluable support, which definitely kept me on the go while writing this book. I also want to thank my close friends for giving me lots of helpful feedback, notably Sascha Björn Bolz with regard to providing the artwork for Canyon Bunny. Last but not least, I want to thank Klaus "keith303" Spang for providing the music track as well as the whole team from Packt Publishing, including all the numerous reviewers involved, for 
their great work in producing a high quality book.

About the Reviewers

Ebenezer Edelman is a British computer programmer currently living in South Africa. He has an eclectic and diverse set of interests ranging from technology, engineering, and science to literature, photography, videography, and music. His hobbies include playing the piano, designing rocket engines, and occasionally a game of chess.

He started game development by learning C from the manual of a C compiler and developing simple text-based games. Then, after getting to grips with C++ and the DirectX SDK, he attempted to develop a 3D physics sandbox game, which never got past the beta stage. After that, he learned C# and the XNA framework and made several 2D games before deciding to get involved in mobile game development. He did this using Java and the LibGDX framework, which he used to get some of his old 2D games to Android. He is constantly looking to broaden his knowledge, and he now uses Research In Motion's open source C++ game engine gameplay3d.

In addition, he has experience of Windows Forms (C#), the GTK+ toolkit (Vala), the Qt toolkit (C++), the Android SDK (Java), as well as the x86 Assembly language, Python, PHP, JavaScript, and HTML/CSS.

His personal website and blog is located at http://EbenezerEdelman.tk/, and he is on Twitter (@EbenezerEdelman) and Google Plus (+EbenezerEdelman).

Matthias Markowski is a passionate game developer and video game enthusiast who focuses on the field of Graphics Programming. He began his professional career in 2005 through his involvement in the demoscene. He has contributed to the development of the fast-paced action MMOG (Massively Multiplayer Online Game) "Black Prophecy" and the Wii U casual game "Your Shape Fitness Evolved 2013". He is currently employed at Ubisoft Blue Byte, known as a creator of excellent strategy games, located in Düsseldorf, Germany.

You can view his portfolio and contact details at http://mmarkowski.carbonmade.com.

David Saltares Márquez works at the award-winning developer Crytek as a games programmer. The Nottingham-based studio of the company behind the Crysis series was his jump into the AAA industry in 2012. Since then, he has been part of the Artificial Intelligence team, developing behaviors, pushing character fidelity forward, and developing systems that are now part of CryENGINE.

He obtained his BSc in Computing Science from Cádiz University (Spain) where he founded the games development society (ADVUCA) in collaboration with other passionate classmates. Through the society, he organized several talks and workshops with a strong focus on open source software, all of which were a great success.

By always working on side projects, he the joined the Libgdx community, attracted by the richness of its features, open source nature, multiplatform capabilities, and the hospitality of its developers. Libgdx allowed him to create various games such as Freegemas (https://github.com/siondream/freegemas-gdx) and Math Maze (http://siondream.com/blog/games/math-maze/). In return, he contributed to the maps' API and is very active on the forums.

Further information is available on his blog (http://siondream.com), where he talks in depth about Libgdx, programming, personal projects, and his experience in game jams such as Ludum Dare (http://siondream.com/blog/game-jams/).

Chris Moeller is a founder of the game studio Ackmi Design and Engineering. He has been building computers since the age of nine and has been programming for more than 10 years. He had the opportunity to work for software companies as a PHP developer, Java QA engineer, and Flash developer, and he currently works primarily for Android. He has been an enthusiastic gamer for most of his life and has created many game prototypes as well as several finished games. He writes game tutorials on his blog at www.chrismweb.com, and most of his new games can be found through his company website at www.ackmi.com, which he runs with his wife, Megan.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Since personal computers have conquered our private homes, video games have become more and more popular and eventually a multimillion dollar business for big video game companies. With the introduction of mobile devices such as smartphones and tablets, the market for video games has experienced another significant increase; in particular, it has now become open to independent game developers with small budgets.

For game developers, it is essential to have tools at hand that provide fundamentals which allow rapid prototyping and cost-effective implementation of their creative ideas. This is where Libgdx comes into play.

Libgdx, as a Java-based game development framework, provides a unified access layer to handle all the supported platforms. Libgdx also makes use of C/C++ to achieve cross-platform support as well as to boost the application performance for mission critical tasks.

This book will show you how easy it is to develop cross-platform games by walking you through a complete game development cycle using the free and open source library Libgdx. Besides this, you will also learn about common game structure and the involved requirements.

You will be introduced to the key features of Libgdx and you will learn how to develop a game with ease and speed up your development cycles. In ten easy-to-follow chapters, you are going to develop your first Libgdx cross-platform game and add more and more game functionalities as you progress further through this book.

The special features will also make you acquainted with advanced programming techniques such as animations, physics simulations, and shader programs that enhance your games in both their gameplay and visual presentation.

By the end of this book, you will have a fully working 2D game that will run on Windows, Linux, Mac OS X, WebGL-capable browsers, and Android. You will also have all the skills required to extend the game further or to start developing your own cross-platform games.

What this book covers

Chapter 1, Introduction to Libgdx and Project Setup, covers how to install and configure the development environment and introduces you to the project setup tool that comes with Libgdx. Then, we will take a first look at the basics of what a game needs to come alive.

Chapter 2, Cross-platform Development – Build Once, Deploy Anywhere, explains the supported target platforms and how to deploy and run our application on each platform using a demo application. For the first overview of Libgdx's API, we will take a glance at each module. Then, the Application Cycle will be introduced, and we will take a look at how to debug and manipulate our code at runtime.

Chapter 3, Configuring the Game, brings us from our demo application to a real game by setting up a new project called Canyon Bunny. We will work on this project throughout the rest of the book and extend it from chapter to chapter with new features. Since Libgdx is a framework, we will first have to build our program architecture by using UML class diagrams to structure our game engine.

Chapter 4, Gathering Resources, describes how to gather all the resources (assets) needed for Canyon Bunny including graphics, audio files, level data, and so on. We will also find out how to load, track, and organize assets efficiently. Finally, it is time to think about how level data is going to be handled so that we are able to populate our game world with objects.

Chapter 5, Making a Scene, covers how to start implementing the first game objects such as rocks, mountains, and clouds, and how to use the assets that we added in Chapter 4, Gathering Resources. In order to visualize the game scene, a level loader is needed to put our game objects in their right places in the game world. Typically, games have a user interface to give feedback about their current status, so we will add a game GUI to Canyon Bunny that displays the player's high score, remaining extra lives, and so on.

Chapter 6, Adding the Actors, explains how to add the remaining game objects for Canyon Bunny, including the player character and collectible items to complete our game. We will also add simple physics for player movement and basic collision detection. Additionally, the game logic will be extended so that it is able to detect the "life lost" and "game over" conditions.

Chapter 7, Menus and Options, describes how to create a menu system with widgets such as buttons, labels, and checkboxes to enrich the overall game experience. Furthermore, we will add an Options window where the player can adjust the game settings.

Chapter 8, Special Effects, covers how to make use of particle systems and how to apply interpolation algorithms to create impressive effects such as dust clouds; a smooth, following camera; floating rocks; and parallax scrolling for mountains in the background. Using special effects will spice up the appearance of your game.

Chapter 9, Screen Transitions, introduces screen transitions. We will dive into enhanced visual effects using OpenGL's Framebuffer Objects for offscreen rendering into video memory. This will allow us to create seamless transitions for an improved user experience when switching from one screen to another. For Canyon Bunny, we will create a variety of transition effects.

Chapter 10, Managing Music and Sound Effects, will walk you through a list of recommended sound generators and discuss their differences. Then, we will take a look at Libgdx's Audio API and demonstrate how to use it by creating an audio manager. We do this so that handling all our audio playback needs become a breeze.

Chapter 11, Advanced Programming Techniques, introduces you to some advanced programming techniques that will guide you to the next level of game programming. We will build up basic knowledge about the Box2D API that enables us to create believable physics simulations in games. Additionally, we will discuss the topic of shader programs using the example of a monochrome image filter effect. Lastly, we will show you how to make use of the accelerometer hardware commonly available in modern smartphones and tablets, which allows controlling the game by tilting the device.

Chapter 12, Animations, explains how to polish up the game by adding animations. We will cover two different approaches to animate the game menu and the game world. Finally, we will implement a state machine to allow event-based animations for the player character.

What you need for this book

Libgdx is a cross-platform game development framework. For development, you will need a computer running either Windows (Vista/7/8), Linux (for example, Ubuntu), or Mac OS X (10.5+).

Additionally, you will need to download the Libgdx framework for game development. You can download Libgdx from https://code.google.com/p/libgdx/downloads/list. Please download Version 0.9.7 of Libgdx, as this is the version that is used in this book.

The Integrated Development Environment (IDE) used in this book is Eclipse. You can download the Eclipse IDE from http://www.eclipse.org/.

To develop games for the Android platform, you will need an Android device running Android 2.2 (Froyo) or higher and the official Android Software Development Kit (SDK) that can be downloaded from http://developer.android.com/sdk/index.html.

Who this book is for

This book is written for software developers who are new to game development and to Libgdx in particular. It is assumed that you have some experience in Java to be able to follow the discussed code in this book.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "The main class of the demo application is MyDemo.java."

A block of code is set as follows:

@Override public void dispose() { batch.dispose(); texture.dispose(); }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public void update (float deltaTime) { updateMotionX(deltaTime); updateMotionY(deltaTime); // Move to new position position.x += velocity.x * deltaTime; position.y += velocity.y * deltaTime; }

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "A new tab titled Development Mode should open at the bottom."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

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:

WindowsLinuxMac OS XAndroid (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 platformsCustom OpenGL ES 2.0 bindings for Android 2.0 and aboveLow-level OpenGL helpers:
Vertex arrays and vertex buffer objectsMeshesTexturesFramebuffer objects (GLES 2.0 only)Shaders, integrating easily with meshesImmediate mode rendering emulationSimple shape renderingAutomatic software or hardware mipmap generationETC1 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 libraryOrthographic cameraHigh-performance sprite batching and caching, and handling OpenGL ES 1.x and 2.0 differences transparentlyTexture atlases with whitespace stripping support, which are either generated offline or onlineBitmap 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 systemTMX tile map support2D scene-graph API2D UI library, based on scene-graph API, and fully skinable
High-level 3D APIs:
Perspective cameraDecal batching for 3D billboards or particle systemsBasic loaders for Wavefront OBJ and MD5Work 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 OGGDirect 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 platformsRead-only filesystem emulation for JavaScript backendBinary file support for JavaScript backendPreferences 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 supportJSON writer and reader with POJO (de-)serialization supportXML writer and reader

Tools

Gdx Setup UI for easy project setupParticle editorTexture packerBitmap 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 Zechnerwho 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 toUser 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 fielddefines 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.