Libgdx Cross-platform Game Development Cookbook
()
About this ebook
Libgdx is a very popular open source, cross-platform, Java-based game development framework that enables you to write your code once and deploy it to Windows, Mac, Linux, Android, iOS, and browsers.
Supported by code samples for each topic, this book will take you through the features of Libgdx, from the very basic aspects to the most advanced ones. Beginning with an overview of the framework and project creation, the book moves on to the 2D graphics API that enables you to create efficient and visually rich games. You will then explore input detection and audio and file handling, followed by details of how to make use of amazing features such as Box2D rigid body physics, lighting, and artifical intelligence techniques to name a few. You will also discover how to modify Libgdx to suit your needs and share your creation with the world.
Related to Libgdx Cross-platform Game Development Cookbook
Related ebooks
PhantomJS Cookbook Rating: 0 out of 5 stars0 ratingsMeteor Cookbook Rating: 5 out of 5 stars5/5AngularJS Web Application Development Cookbook Rating: 0 out of 5 stars0 ratingsHTML5 Data and Services Cookbook Rating: 5 out of 5 stars5/5Node Cookbook Rating: 0 out of 5 stars0 ratingsLiferay 6.x Portal Enterprise Intranets Cookbook Rating: 0 out of 5 stars0 ratingsAndroid Native Development Kit Cookbook Rating: 0 out of 5 stars0 ratingsOuya Unity Game Development Rating: 0 out of 5 stars0 ratingsSwift 2 Design Patterns Rating: 0 out of 5 stars0 ratingsAndroid: Game Programming Rating: 0 out of 5 stars0 ratingsCorona SDK Mobile Game Development: Beginner's Guide - Second Edition Rating: 0 out of 5 stars0 ratingsMeteor Design Patterns Rating: 0 out of 5 stars0 ratingsHTML5 for Flash Developers Rating: 5 out of 5 stars5/5Xamarin Mobile Application Development for Android - Second Edition Rating: 0 out of 5 stars0 ratingsAndroid Application Development with Maven Rating: 0 out of 5 stars0 ratingsCryENGINE 3 Game Development Beginner's Guide Rating: 0 out of 5 stars0 ratingsAJAX Interview Questions, Answers, and Explanations: AJAX Certification Review Rating: 0 out of 5 stars0 ratingsGameSalad Essentials Rating: 0 out of 5 stars0 ratingsIntelliJ IDEA Essentials Rating: 0 out of 5 stars0 ratingsjQuery 2.0 Development Cookbook Rating: 0 out of 5 stars0 ratingsjQuery Game Development Essentials Rating: 0 out of 5 stars0 ratingsAndroid Studio Electric Eel Essentials - Java Edition: Developing Android Apps Using Android Studio 2022.1.1 and Java Rating: 0 out of 5 stars0 ratingsBootstrap Site Blueprints Rating: 0 out of 5 stars0 ratingsLearning LibGDX Game Development - Second Edition Rating: 0 out of 5 stars0 ratingsCSS Mastery: Styling Web Pages Like a Pro Rating: 0 out of 5 stars0 ratingsOpenCart Theme and Module Development Rating: 0 out of 5 stars0 ratingsNode Web Development, Second Edition Rating: 0 out of 5 stars0 ratingsNW.js Essentials Rating: 0 out of 5 stars0 ratingsASP.NET jQuery Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsHTML5 Game Development with GameMaker Rating: 0 out of 5 stars0 ratings
Computers For You
How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsThe Invisible Rainbow: A History of Electricity and Life Rating: 5 out of 5 stars5/5Uncanny Valley: A Memoir Rating: 4 out of 5 stars4/5The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution Rating: 4 out of 5 stars4/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5Elon Musk Rating: 4 out of 5 stars4/5Standard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5CompTIA Security+ Get Certified Get Ahead: SY0-701 Study Guide Rating: 5 out of 5 stars5/5ChatGPT 4 $10,000 per Month #1 Beginners Guide to Make Money Online Generated by Artificial Intelligence Rating: 0 out of 5 stars0 ratingsEverybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5The Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5101 Awesome Builds: Minecraft® Secrets from the World's Greatest Crafters Rating: 4 out of 5 stars4/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 5 out of 5 stars5/5The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling Rating: 0 out of 5 stars0 ratingsLearning the Chess Openings Rating: 5 out of 5 stars5/5CompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratingsPeople Skills for Analytical Thinkers Rating: 5 out of 5 stars5/5
Reviews for Libgdx Cross-platform Game Development Cookbook
0 ratings0 reviews
Book preview
Libgdx Cross-platform Game Development Cookbook - David Saltares Márquez
Table of Contents
Libgdx Cross-platform Game Development Cookbook
Credits
About the Authors
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
Downloading the color images of this book
Errata
Piracy
Questions
1. Diving into Libgdx
Introduction
Setting up a cross-platform development environment
Getting ready
How to do it…
Java Development Kit
Windows and Mac users
GNU/Linux users
Eclipse
Android SDK
Mac users
GNU/Linux users
All users
Eclipse plugins
XCode
Fixing character encoding and line endings
Making sure everything is in order
How it works…
There's more…
See also
Creating a cross-platform project
Getting ready
How to do it…
How it works…
There's more…
See also
Understanding the project structure and application life cycle
Getting ready
How to do it…
Using logging to get to know the application life cycle
Starter classes and configuration
Desktop starter
Android starter
HTML starter
iOS starter
How it works…
There's more…
Living comfortably with ApplicationAdapter
Managing a multiscreen application with Game
See also
Updating and managing project dependencies
Getting ready
How to do it…
Gradle build file primer
Updating existing dependencies
Adding Libgdx extensions
Bullet
Core
Desktop
Android
iOS
FreeTypeFont
Core
Desktop
Android
iOS
Controllers
Core
Desktop
Android
HTML5
Box2D
Core
Desktop
Android
iOS
HTML5
Tools
Core
Desktop
AI
Core
Android
HTML
Adding external repositories
Adding additional file dependencies
Managing GWT dependencies
There's more…
See also
Using source control on a Libgdx project with Git
Getting ready
How to do it…
How it works…
Basic operations
Git branches
Gitignore files
There's more…
See also
Importing and running the Libgdx official demos
Getting ready
How to do it…
How it works…
There's more…
2. Working with 2D Graphics
Introduction
Texture rendering with SpriteBatch
Getting ready
How to do it…
How it works…
2D rendering using 3D techniques
Coordinate system and camera setup
Assets location in Libgdx
Draw order
Texture filters
There's more…
See also
More effective rendering with regions and atlases
Getting ready
How to do it…
Packing PNG files into an atlas
Rendering regions of an atlas
How it works…
Atlas file format
How SpriteBatch works
A note on texture size limitations
There's more…
See also
Taking advantage of Libgdx sprites
Getting ready
How to do it…
How it works…
There's more…
Using bounds for collision detection
See also
Rendering sprite-sheet-based animations
Getting ready
How to do it…
How it works…
There's more…
Using different play modes
Checking when an animation has finished
Handling a character with many animations
See also
Understanding orthographic cameras
Getting ready
How to do it…
How it works…
There's more…
Rendering UI on top of the game world
Split screen
See also
Using ShapeRenderer for debug graphics
Getting ready
How to do it…
Rendering lines
Rendering circles
Rendering rectangles
Rendering points
Rendering triangles
How it works…
There's more…
See also
Handling multiple screen sizes with viewports
Getting ready
How to do it…
How it works…
There's more…
Getting the most out of Viewport
Working with two cameras and viewports
Floating elements
Build your own Viewport implementation
See also
3. Advanced 2D Graphics
Introduction
Achieving juicy effects with particles
Getting ready
How to do it…
The basics of Particle Editor
Rendering particle effects with Libgdx
How it works…
There's more…
See also
Frame buffers and image composition
Getting ready
How to do it…
How it works…
There's more…
Welcome to the world of shaders
Getting ready
How to do it…
How it works…
Data types
Vertex attributes
Uniforms
OpenGL ES precision specifiers
There's more…
The sepia effect
Inverted colors
Passing parameters into shader programs
Getting ready
How to do it…
How it works…
There's more…
Detecting shader compiler errors
More efficient uniform settings
2D depth of field shader
Getting ready
How to do it…
There's more…
See also
Embedding a Libgdx window into a Java desktop application
Getting ready
How to do it…
How it works…
There's more…
See also
4. Detecting User Input
Introduction
Detecting user input via event polling
Getting ready
How to do it…
How it works…
There's more…
Checking input availability
Showing the on-screen keyboard
Detecting user input via event listening
Getting ready
How to do it…
Event polling versus event listening
How it works…
There's more…
Managing multiple listeners at once
Getting ready
How to do it…
How it works…
See also
Detecting more complex gestures
Getting ready
How to do it…
How it works…
There's more…
Gesture polling
Introducing the controllers API
Getting ready
How to do it…
Including the controllers extension
Enumerating controllers
Controller state polling
Controller event listening
How it works…
There's more…
Controller mappings
Handling disconnections
See also
Input mapping for cross-platform development
Getting ready
How to do it…
Input contexts
Input profiles
Event notifications with InputActionListener
Input mapping in action
How it works…
There's more…
5. Audio and File I/O
Introduction
Playing short sound effects
Getting ready
How to do it…
How it works…
There's more…
Handling sounds individually
Changing the volume
Creating looping sounds
Managing effect priorities
See also
Audio streaming for background music
Getting ready
How to do it…
How it works…
There's more…
Checking the playback state
Looping the background music
See also
Optimizing audio files to reduce download sizes
Getting ready
How to do it…
How it works…
There's more…
See also
Procedural audio generators
Getting ready
How to do it…
How it works…
There's more…
See also
Engine sounds with dynamic audio
Getting ready
How to do it…
How it works…
There's more…
Controlling direction through panning
Music transitions
See also
The 2D space sound system
Getting ready
How to do it…
How it works…
There's more…
See also
The first approach to file handling in Libgdx
Getting ready
How to do it…
Retrieving basic information from files
Traversing tree structures
Writing to and reading from files
Copying and deleting files and directories
How it works…
There's more…
Creating temporary files
Filtering directory listings
File streaming
See also
Using preferences to store game states and options
Getting ready
How to do it…
How it works…
There's more…
See also
The XML parsing primer
Getting ready
How to do it…
How it works…
There's more…
See also
JSON serialization and deserialization
Getting ready
How to do it…
Reading objects from JSON
Writing objects to JSON
Manual JSON parsing
How it works…
There's more…
The Serializable interface
The Serializer interface
See also
6. Font Rendering
Introduction
Generating and rendering bitmap fonts
Getting ready
How to do it…
Using Hiero to generate bitmap font files
Rendering bitmap font files with Libgdx
How it works…
There's more…
See also
Baking effects into fonts using Hiero
Getting ready
How to do it…
How it works…
See also
Scaling friendly font rendering with distance fields
Getting ready
How to do it…
Generating distance field fonts with Hiero
Distance field fonts shader
Rendering distance field fonts in Libgdx
How it works…
There's more…
Dynamic font effects using distance fields
Getting ready
How to do it…
How it works…
There's more…
7. Asset Management
Introduction
Getting to know AssetManager
Getting ready
How to do it…
How it works…
There's more…
See also
Asynchronous asset loading
Getting ready
How to do it…
How it works…
There's more…
See also
Creating custom asset loaders
Getting ready
How to do it…
Writing our own asset type
Writing our own asset loader
Summarizing...
How it works…
There's more…
See also
Managing groups of assets for bigger games
Getting ready
How to do it…
Giving shape to the idea
Empowering AssetManager
How it works…
There's more…
See also
8. User Interfaces with Scene2D
Introduction
Introducing the Scene2D API
Getting ready
How to do it…
Creating a custom actor
Rendering your custom actor
Manipulating an actor
Simple actions
Complex actions
How it works…
There's more…
See also
Widget collection overview
Getting ready
How to do it…
Label
Image
Button
TextButton
ImageButton
ImageTextButton
CheckBox
TextField
List
ScrollPane
SelectBox
ProgressBar
Slider
Touchpad
Stack
Tree
SplitPane
Window
Dialog
How it works…
There's more…
See also
Creating a basic menu screen using tables
Getting ready
How to do it…
How it works…
Expand
Fill
Uniform
Sizing
Padding and spacing
Alignment
Columns and rows
Defaults
There's more…
See also
Skin customization
Getting ready
How to do it…
How it works…
There's more…
See also
Creating new widgets
Getting ready
How to do it…
Creating a widget
Using a widget
How it works…
There's more…
9. The 2D Maps API
Introduction
Creating maps with Tiled and loading them into Libgdx
Getting ready
How to do it…
Creating a basic map with Tiled
Loading and rendering a Tiled map in Libgdx
How it works…
There's more…
Adding and querying map metadata
Getting ready
How to do it…
Object layers and properties in Tiled
Querying map metadata from Libgdx
How it works…
There's more…
See also
Developing your own map loaders and renderers
Getting ready
How to do it…
There's more…
10. Rigid Body Physics with Box2D
Introduction
Introducing Box2D
Getting ready
How to do it…
How it works…
There's more…
See also
Introducing more complex shapes
Getting ready
How to do it…
Generating JSON shape data
Loading JSON shape data into Libgdx
How it works…
There's more…
See also
Introducing joints
Getting ready
How to do it…
WeldJoint
DistanceJoint
RopeJoint
FrictionJoint
RevoluteJoint
PrismaticJoint
PulleyJoint
GearJoint
WheelJoint
There's more…
See also
Real-life joints example – bike simulator
Getting ready
How to do it…
There's more…
Reacting to collisions
Getting ready
How to do it…
How it works…
There's more…
See also
Sensors and collision filtering
Getting ready
How to do it…
Sensors
Group collision filtering
Flexible collision filtering
How it works…
There's more…
See also
Querying the world
Getting ready
How to do it…
Raycasting
Area querying
How it works…
There's more…
See also
Building a physics world from level data
Getting ready
How to do it…
Defining materials
Generating the physics metadata
Populating your world
How it works…
There's more…
See also
Implementing a deferred raycaster
Getting ready
How to do it…
The RayCastManager class
Using RayCastManager
How it works…
There's more…
See also
The fixed timestep approach
Getting ready
How to do it…
Variable timestep
Fixed timestep
Fixed timestep with interpolation
There's more…
See also
11. Third-party Libraries and Extras
Introduction
Making libraries compatible with GWT
Getting ready
How to do it…
There's more…
See also
Managing platform-specific code
Getting ready
How to do it…
There's more…
Smooth animations with Universal Tween Engine
Getting ready
How to do it…
Creating your accessor
Library usage
Tween – a core class
Organizing tweens
How it works…
Dynamic 2D lighting with Box2DLights
Getting ready
How to do it…
How it works…
RayHandler
Types of lights
There's more…
Adding support for localization
Getting ready
How to do it…
Creating language files
Managing languages
Usage example
There's more…
See also
Finite state machine and messaging
Getting ready
How to do it…
Creating the agents
Usage example
How it works…
There's more…
Component-based entity systems with Ashley
Getting ready
How to do it…
How it works…
There's more…
See also
Skeletal animations with Spine
Getting ready
How to do it…
How it works…
There's more…
12. Performance and Optimizations
Introduction
Profiling your application with VisualVM
Getting ready
How to do it…
Installing VisualVM
Changing the launcher
Monitoring and profiling
How it works…
There's more…
Using Libgdx features to avoid garbage collection
Getting ready
How to do it…
Collections
Caching
Object pooling
There's more…
Avoiding unnecessary render calls with frustum culling
Getting ready
How to do it…
How it works…
There's more…
13. Giving Back
Introduction
Releasing your Libgdx game on desktop
Getting ready
How to do it…
There's more…
See also
Releasing your Libgdx game on Android
Getting ready
How to do it…
There's more…
Releasing your Libgdx game on iOS
Getting ready
How to do it…
There's more…
Releasing your Libgdx game on browsers
Getting ready
How to do it…
There's more…
Working from sources
Getting ready
How to do it…
How it works…
See also
Creating a new test for your fresh feature
Getting ready
How to do it…
Sending a pull request on GitHub
Getting ready
How to do it…
There's more…
See also
Index
Libgdx Cross-platform Game Development Cookbook
Libgdx Cross-platform Game Development Cookbook
Copyright © 2014 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 authors, 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: October 2014
Production reference: 1221014
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78328-729-1
www.packtpub.com
Cover image by Pratyush Mohanta (<[email protected]>)
Credits
Authors
David Saltares Márquez
Alberto Cejas Sánchez
Reviewers
Si Fleming (PhD)
Joost van Ham (Xoppa)
Manuel Palomo-Duarte
Jon Renner
André Schmode
Commissioning Editor
Ashwin Nair
Acquisition Editor
Nikhil Karkal
Content Development Editor
Mohammed Fahad
Technical Editors
Taabish Khan
Venu Manthena
Copy Editors
Dipti Kapadia
Sayanee Mukherjee
Laxmi Subramanian
Project Coordinator
Danuta Jones
Proofreaders
Simran Bhogal
Maria Gould
Ameesha Green
Paul Hindle
Indexers
Hemangini Bari
Rekha Nair
Graphics
Ronak Dhruv
Abhinash Sahu
Production Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
About the Authors
David Saltares Márquez is a C++ software developer at a top-tier financial data company. He was an Artificial Intelligence programmer at Crytek, UK, for two years, where he developed emergent systems for Homefront: The Revolution. He then moved to Sony Computer Entertainment Europe to work on multimedia applications for PlayStation 4. He is part of the Libgdx core team, works on small indie games in his spare time, loves game jams, and often delivers presentations at universities. Find out more about his work on his personal blog at http://siondream.com.
To Anda, who stood by me during good and bad times, and my parents, who unconditionally encouraged me from afar.
Alberto Cejas Sánchez is an indie game programming enthusiast who graduated with an MSc in Computer Science and whose work revolves around games and simulations across 2D/3D technologies with different target platforms. He has also worked on automatic game code generation tools.
To those responsible for making me feel proud as a son.
About the Reviewers
Si Fleming (PhD) is currently a senior engineer at Sony Computer Entertainment Europe with a career spanning over a decade. He holds a PhD in Computer Science from the University of Sussex where his research focused on distributed systems, ad hoc social networks, Q & A, security, and privacy. He has taken part in game jams including #OneGameAMonth and is currently working on several games using Libgdx.
Joost van Ham (Xoppa) founded the Xoppa company in 2001 and graduated in Computer Science in the Netherlands in 2004. Since then, he has served a wide variety of companies with their business automation. He's been working on Libgdx since 2012, where his main focus is on the 3D API, linear algebra, and 3D physics wrapper. He's also the author of a series of comprehensive tutorials covering 3D game development with libGDX, which can be found at http://blog.xoppa.com.
Manuel Palomo-Duarte is currently a Lecturer and Degree Coordinator for Computer Science at the University of Cadiz (Spain), where he received his PhD in 2011. He has been working for several years as a Director to the Free Software and Open Knowledge office at the same university and is a board member of Wikimedia Spain. His teaching focuses on subjects related to open data and video game development using open source software. His main research interests are learning technologies, serious games, and collaborative development. In these fields, he has published different contributions in peer-reviewed journals and research conferences.
André Schmode is a 40-year-old German developer with a passion for video games. He lives in Berlin and holds a degree in Business Computer Science. He started developing with Commodore C16, C64, and Amiga, turned over to Visual Basic, and finally fell in love with Java. He started development with Libgdx in 2012 and released the game bubblr – dummy in trouble for Android devices and OUYA consoles. Game development is just a hobby for him. He loves to be creative and bring his fantasies to life. The only limit when developing a video game is his imagination! (and minor technical difficulties).
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
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 Packt
Copy and paste, print and bookmark content
On 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
Libgdx is a powerful Java-based open source cross-platform game framework. It allows developers to target Windows, Mac, Linux, Android, iOS, and HTML5 with a single codebase, sparing them the hassle of dealing with low-level, platform-specific details.
For more information, please refer to http://libgdx.badlogicgames.com/.
Through a clean and simple API, Libgdx offers a vast set of features, which are as follows:
Low-level OpenGL access: This includes vertex arrays, meshes, framebuffers, shaders, and immediate mode renderer
2D graphics: This includes bitmaps, texture atlases, particles, scene graph, user interface, and maps
3D graphics: This includes model loading, lighting, decal batching, particles, and so on
Audio: This includes streaming music, sound effects (MP3, WAV, and OGG), pitch control, and direct access to recording devices
Input: This includes keyboard, mouse, touch, accelerometer, compass, and controller events as well as gesture detection
Math and physics: This includes matrices, vectors, shapes, interpolators, frustum, intersection utilities, and full Box2D and Bullet physics JNI wrappers
File I/O: This includes cross-platform file access, preferences storage, XML, and JSON parsing
Utilities: This includes fast custom collections and easy multiresolution handling
Tools: This includes project creation, particle editor, bitmap font generator, and texture packer
Libgdx is incredibly fast, thanks to the use of JNI wrappers and heavy emphasis on avoiding garbage collection. This becomes crucial when deploying on mobile devices and browsers. Its framework nature allows you to choose which components to use as it does not enforce a single way of working like most engines do.
The community behind the framework is large, welcoming, and always willing to provide support. The GitHub repository shows how active the project is, with many commits every day, constant releases, and rich documentation. For more information, refer to https://github.com/libgdx/libgdx.
Thanks to its permissive Apache 2.0 license, Libgdx can be used for both commercial and noncommercial projects without having to necessarily disclose the source. According to AppBrain, 1.44 percent of all the Android applications (both games and nongames) are built on top of it, which reinforces its flexibility and ease of use. For more information, refer to http://appbrain.com/stats/libraries/details/libgdx/libgdx.
This book provides excellent coverage of the aforementioned systems focusing on 2D game development. Each chapter covers a set of related features through a series of recipes. A recipe explains with simple steps how to carry out a particular task with Libgdx such as rendering a texture on the screen. The practical approach will give you a very good insight on how things actually work, preparing you to use this technology on real-life projects.
After reading through the recipes in this book, you will have a solid understanding of how all the systems in Libgdx work and how to better leverage them in order to implement your games. The good practices exposed here will give you an edge to produce clean and efficient code.
What this book covers
Chapter 1, Diving into Libgdx, introduces the reader to the Libgdx development environment so as to get ready for the rest of the book. It also presents the basic architecture of the framework, how to run applications across devices, and how to put a project under source control.
Chapter 2, Working with 2D Graphics, covers the most important aspects of the Libgdx 2D API. The readers will learn how to render and animate textures, work with cameras, and deal with different resolutions.
Chapter 3, Advanced 2D Graphics, shows the reader how to achieve juicy effects with particles, shaders, and image composition.
Chapter 4, Detecting User Input, explains how to make your applications interactive across different devices. Keyboard, mouse, touch, and controller-based inputs are all found in this chapter.
Chapter 5, Audio and File I/O, shows readers how to play background music and sound effects to give that extra sparkle to the project. It also covers how to use the file's API and read popular formats such as JSON and XML.
Chapter 6, Font Rendering, details the different approaches to render text through Libgdx. Moreover, it also teaches how to overcome common pitfalls such as special characters and font scaling.
Chapter 7, Asset Management, provides information on how to control your assets' life cycle so as to accommodate low memory devices and make the most out of the hardware. It also gives insight into how to achieve asynchronous loading, so apps stay responsive while they stream content.
Chapter 8, User Interfaces with Scene2D, covers the powerful Libgdx scene hierarchy API focusing on how to build UI layouts. Moreover, it goes as far as skinning and custom widget creation. The reader will learn how to create great menus and in-game HUDs.
Chapter 9, The 2D Maps API, explains the simple Libgdx mechanisms to load and render levels created with tools such as Tiled as well as to query their metadata. The maps 2D API also allows users to provide loaders and renderers for additional formats.
Chapter 10, Rigid Body Physics with Box2D, shows the reader how to use the many features of the popular physics library that comes with Libgdx. Bodies, shapes, joints, sensors, collision handling, level geometry, raycasting, and fixed timestep are all covered in this chapter.
Chapter 11, Third-party Libraries and Extras, goes through the most popular Libgdx extensions, so the reader can make use of their enhancements. It covers a wide range of topics such as lighting, skeletal animation, localization, and entity systems.
Chapter 12, Performance and Optimizations, provides the readers with advice to achieve their performance targets. This becomes crucial when targeting mobile devices and browsers.
Chapter 13, Giving Back, lays out the process of publishing a finished application as well as contributing to the main Libgdx repository.
What you need for this book
As a minimum, you need a computer running Windows, Mac, or a Linux distribution that also supports hardware acceleration. No need to worry; currently, even the most considerably old machines support this. Additionally, to target Android devices, a phone or a tablet running Android 2.2 or higher is required. In order to target iOS, a Mac with XCode is needed, and when testing on a real device, an Apple developer subscription becomes a must.
All software dependencies are free to use even for commercial purposes. However, the Apple developer license is subject to yearly payments.
Installation instructions for additional software will be provided when needed.
Who this book is for
This book is aimed at developers who are already familiar with object-oriented programming principles, know the basics of game development, and want to use the power of Libgdx to make awesome cross-platform games without the hassle of having to deal with platform-specific nonsense.
Although Libgdx is based on Java, having experience with the language is only recommended and not a must. It can easily be learned as you go, even more so when coming from C++ or C#.
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, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The action takes place within the overridden processEntity() method responsible for the logic
A block of code is set as follows:
public class DesktopResolver implements PlatformResolver {
@Override
public void rateGame() {
System.out.println(Desktop
);
Gdx.net.openURI(https://facebook.com
);
}
}
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 String getCurrentLanguage() { return currentLanguage;
}
public void setCurrentLanguage(String name) {
if(languages.containsKey(name.toLowerCase()))
currentLanguage = name;
}
Any command-line input or output is written as follows:
tar –xzvf android-sdk.r22.2.1-linux.tgz
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: Install the Gradle IDE entry and restart Eclipse for the last time.
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. This book is full of rich working examples you can experiment with. Access the following link to download the most up-to-date version: https://github.com/siondream/libgdx-cookbook.
Downloading the color images of this book
We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from: https://www.packtpub.com/sites/default/files/downloads/7291OS_coloredimages.pdf.
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 errata submission form 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. Diving into Libgdx
In this chapter, we will cover the following recipes:
Setting up a cross-platform development environment
Creating a cross-platform project
Understanding the project structure and application life cycle
Updating and managing project dependencies
Using source control on a Libgdx project with Git
Importing and running the Libgdx official demos
Introduction
Before thinking about how to render an animated character onscreen, it is very important that you prepare all the required tools to create cross-platform applications with Libgdx and understand its basic principles. This is, precisely, the purpose of this initial chapter.
First, we will cover how to install everything that is required for the three major operating systems, Windows, Mac, and GNU/Linux. Though we all know you want to go straight to the fun bit, a stable and productive working environment is vital in order to avoid future headaches. After we make sure that all is in order by testing a sample project, it will be time to take a closer look at how all Libgdx projects are structured.
Often, a developer wants to use a newer version of Libgdx or some third-party library because it includes an incredible feature or solves a problem they were losing sleep over. For these reasons, it will prove very useful to know how to properly update a project so as to enjoy some fresh goodies.
Finally, as you are probably very much aware, using source control for every single one of your endeavors is surely a life saver. Not only does it give us a backup system straightaway, but it also empowers us to share and keep track of the changes in the repository. This is extremely useful when you want to blame someone else for something that went wrong! In this chapter, we will show how to efficiently use source control with a Libgdx project using Git as an example.
Setting up a cross-platform development environment
Once you go through this recipe, you will be able to enjoy Libgdx in all its glory and start developing games for all the supported platforms.
Let's begin with a short disclaimer. For the most part, Libgdx relies on open source software that is widely available at no cost. This means that anyone can target desktops, Android, and browsers using a Windows, Mac, or GNU/Linux distribution. The only restriction applies to iOS, for which you will specifically need a Mac. Moreover, if you wish to test your work on a real device, an Apple developer account is essential and further costs apply.
Getting ready
You need to be aware of the operating system version you will use to pick the right versions of the software packages we will install. The main explanation thread will focus on Windows 8 64-bit, but further comments will be provided whenever there are differences across systems.
Note
Keep in mind that software versions might change after the release of this book, so think of this recipe as more of a guideline than a sacred text. The names of the downloaded packages will typically include the version number, and they will change over time.
How to do it…
Here is our little software shopping list:
Java Development Kit
Eclipse IDE
The Gradle plugin for Eclipse
Android SDK, only for those who want to target Android devices
The RoboVM plugin for Eclipse, only if you want to target iOS
XCode, only for Mac users that want to target iOS
Java Development Kit
Libgdx is based on Java, and therefore, Java Development Kit is a requirement. The installation step is as follows:
Go to Oracle's download site, http://www.oracle.com/technetwork/java/javase/downloads, and click on the latest release of Java SE Development Kit that corresponds to your operating system. Note that you need to differentiate between the x86 and x64 builds.
Note
Be careful; Java 7 is the minimum JDK required, Java 6 will just not work.
Windows and Mac users
Perform the following installation steps:
Run the installer and follow the provided instructions. The process is quite straightforward, but when using Windows, you will have to remember the destination folder you picked; the default folder is C:\Program Files\Java\jdk_version.
You need to tell the system where the JDK is located.
If you are under Windows, right-click on My Computer, click on System Properties, access the Advanced section, and click on Environment Variables. Select New, and enter JAVA_HOME as the name and your installation path as a value. In my case, the value is C:\Program Files\Java\jdk1.7.0_45.
Mac users will have to edit their ~/.bash_profile file and add the following:
export JAVA_HOME=`/usr/libexec/java_home –v 1.7`
GNU/Linux users
Perform the following installation steps:
Move the downloaded package to the desired installation folder and decompress it. You can do this from a desktop environment or the much more classic console. We will assume the file is jdk-7u45-linux-x64.gz; it's in the ~/Downloads directory, and the installation folder is ~/dev/jdk1.7.0_45:
mkdir –p ~/dev/jdkcd ~/Downloadstar –xzvf jdk-17u45-linux-x64.gzmv jdk1.7.0_45 ~/devrm jdk-7u45-linux-x64.gz
Tip
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. This book is full of rich working examples you can experiment with. Access the following link to download the most up-to-date version: https://github.com/siondream/libgdx-cookbook.
In GNU/Linux, the system also needs to know where the JDK is. In order to do so, open the ~/.bashrc file with your text editor of choice and add the following at the bottom:
export JAVA_HOME=$HOME/dev/jdk1.7.0_45export PATH=$PATH:$JAVA_HOME/bin
Close the file, and run the following command to reload the user configuration:
source ~/.bashrc
Note
Alternatively, you can installOpenJDK, the open source implementation of the Java platform.
Eclipse
Eclipse is the most popular IDE for Libgdx game development, and it is thus the one we will focus in this book. If it is not of your liking, you can use IntelliJ IDEA, Netbeans, or any editor along the command line. Perform the following installation steps:
Go to the Eclipse downloads section at http://www.eclipse.org/downloads and select Eclipse Standard. The Eclipse 4 codename, Juno, is the minimum version needed to use the required plugins.
Simply pick the right version for your operating system and wait for it to download; be wary that it is also 32/64-bit sensitive.
Once this is complete, extract the compressed file where you want to use Eclipse from and you will be done.
From a GNU/Linux system, you can do the following:
cd ~/Downloadstar –xzvf eclipse-standard-kepler-SR1-linux-gtk-x86_64.tar.gzmv eclipse ~/devrm eclipse-standard-kepler-SR1-linux-gtk-x86_64.tar.gz
Android SDK
Follow these instructions to install Android Development Kit, which is essential to target Android devices:
Access the download page at http://developer.android.com/sdk.
Scroll down and unfold the View all downloads and sizes section and, again, choose your operating system from the SDK Tools Only section. Google has an easy-to-use installer for Windows users, so if you want to be spared part of the hassle, use the installer.
The installer is really simple. Limit yourself to follow the instructions, and if JDK is properly added to the environment variables, everything should be completely smooth. The installation folder does not really matter.
Mac users
Unzip the package wherever you want, as long as you tell the system where it is. Again, this is done by editing the ~/.bash_profile file and adding something similar to this:
export PATH=$PATH:/dev/android-sdk-mac_x86_64/tools
export PATH=$PATH:/dev/android-sdk-mac_x86_64/platform-tools
GNU/Linux users
Perform the following installation steps:
Unzip the package, move it to the desired installation folder, and add the export location to the PATH environment variable. The commands needed will be something similar to this:
cd ~/Downloadstar –xzvf android-sdk.r22.2.1-linux.tgzmv android-sdk-linux ~/devrm xzvf android-sdk.r22.2.1-linux.tgz
Just like with JDK, edit the ~/.bashrc file and add the following lines at the end:
export PATH=$PATH:~/dev/android-sdk-linux/tools
export PATH=$PATH:~/dev/android-sdk-linux/platform-tools
Again, close the file and reload the ~/.bashrc file:
source ~/.bashrc
After this, go to to the Android SDK folder and run SDK Manager, which will help us install specific packages. On GNU/Linux, you first need to give execution permissions to the user on the SDK folder:
cd ~/dev/android-sdk-linuxchmod –R 744 *
All users
Perform the following steps:
Create an ANDROID_HOME environment variable pointing to the root of Android SDK. This is done the same way as we did with the JAVA_HOME variable in the previous section.
Run SDK Manager found in the tools folder. GNU/Linux users need to run an Android executable.
Several Android SDK tools will appear selected by default; leave them selected. The Google USB driver is not compatible with GNU/Linux, but you should select it if you can.
The SDK tool corresponding to the latest Android version available will be ticked as well. Feel free to choose whichever SDK you prefer, but keep in mind that Libgdx requires Android 2.2 or later.
Note
If you use Android-specific code somewhere in your project, it is advisable to keep SDK for the oldest Android version you want to target. This way, you can ensure compatibility at all times.
Regardless of the Android version you pick, it is always advisable to consider backwards compatibility so as to reach as wide an audience as possible. As a developer, you will want to be thorough when it comes to testing on multiple devices.
Having said this, select Install packages and accept the licenses.
Eclipse plugins
Getting tired? Worry no more, we are getting close to the finish line! We are about to install several plugins that will allow us to manage our build process and target iOS devices:
Gradle (mandatory)
The Google plugin for Eclipse (mandatory)
Developer tools for