Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
LibGDX Game Development By Example
LibGDX Game Development By Example

LibGDX Game Development By Example: Learn how to create your very own game using the libGDX cross-platform framework

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

LibGDX Game Development By Example

Chapter 2. Let's Get These Snakes Out of This Book!

In this chapter, we will start making our first game with the LibGDX framework. We will make a little journey back to one of the very first popular mobile games, Snake. We will start out by looking at LibGDX's update cycle and how textures are handled. Then, we will dive into the world of game making by creating our Snake game!

The following will be covered in this chapter:

  • Why Snake?
  • The game update cycle
  • Introducing the snake
  • Making the snake move
  • Controlling the snake
  • Introducing the collision detection mechanism
  • Increasing the length of the snake once the apple is eaten

Why Snake?

Snake is one of the earliest mobile games that I can remember. I remember playing it many a time, chasing the apple while avoiding contact with the snake's own body. The beauty of the game was that it was a slightly different experience each time you played.

The premise is simple: navigate the snake around the board collecting apples—which increase the length of the snake when consumed—while avoiding collision with the snake itself.

Game update cycle

Before we jump straight into some coding action, let's first take a look at a couple of core classes that will make our lives easier. When you created your project with the setup tool, the core of the game, the MyGDXGame class, which is the default name of the class, extends a class called ApplicationAdapter. This in turn implements an interface called ApplicationListener. Now, you might think these are good enough for us to get going; however, there is a better class that we can extend and that is the Game class.

What is so special about this class? Essentially, it is ApplicationListener that delegates the game to a screen. Every bar method, such as onCreate(), is implemented. This will save us lots of time going forward.

The following code is the Game class from the LibGDX framework:

public abstract class Game implements ApplicationListener {
  protected Screen screen;

  @Override
  public void dispose () {
    if (screen != null) screen.hide();
  }

  @Override
...

Introducing Sammy the snake

Before we start making the Snake game, we need to set up our textures for the snake and the game play area. So, let's remove the default code from our GameScreen class, leaving just our SpriteBatch batch's clear screen calls:

public class GameScreen extends ScreenAdapter {

    private SpriteBatch batch;

    @Override
    public void show() {
        batch = new SpriteBatch();
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    }
}

Next, let's change the color that fills the screen from red to black. We can do this by updating the glClearColor method call to reference the r, g, b, a values of the black Color class:

Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);

If you run the project now, you will find that we are back to our black screen; however, this time, the screen is being cleared every render call. If you don...

Moving Sammy the snake

So, we have Sammy the snake on the screen, sitting there, looking snaky. However, it isn't much of a game. If it were, we could finish the book right here! What we need to do now is get that snake slithering across the screen!

First, let's sort out the playing area. Currently, the resolution is 640 x 480 pixels and the snake texture is 32 x 32. This means we have a grid of 20 x 15—derived by dividing up the resolution by the texture (640/32 = 20, 480/32 = 15)— of the different positions the snake head could be in. The reason we are going to do it this way is because the original game moved with a periodic movement of one snake component at a time. We are going to do the same.

Let's define our timer. We are going to start off with an interval of one second between movements. So let's create a constant field:

    private static final float MOVE_TIME = 1F;

Now, define a variable to keep track of the time:

    private float timer = MOVE_TIME...

Adding the apple

Next up, we need to get our snake eating something. Let's get our apple implemented.

We will need to get our apple to do the following things:

  • Randomly being placed on the screen, not on the snake!
  • Only place one if there isn't an apple on the screen already
  • Disappear when it collides with the snake's head

Right! Let's add the texture:

    private Texture apple;

Then, let's amend our show() method and add the code to instantiate the apple texture:

    apple = new Texture(Gdx.files.internal("apple.png"));

Let's add a flag to determine if the apple is available:

    private boolean appleAvailable = false;
    private int appleX, appleY;

This will control whether or not we want to place one. In the Snake game, the next apple appears after the current apple is eaten; therefore, we don't need any fancy timing mechanism to deal with it. Hence, the apple is not available at the start as we need to place one first. We also specify the variables...

Why Snake?


Snake is one of the earliest mobile games that I can remember. I remember playing it many a time, chasing the apple while avoiding contact with the snake's own body. The beauty of the game was that it was a slightly different experience each time you played.

The premise is simple: navigate the snake around the board collecting apples—which increase the length of the snake when consumed—while avoiding collision with the snake itself.

Game update cycle


Before we jump straight into some coding action, let's first take a look at a couple of core classes that will make our lives easier. When you created your project with the setup tool, the core of the game, the MyGDXGame class, which is the default name of the class, extends a class called ApplicationAdapter. This in turn implements an interface called ApplicationListener. Now, you might think these are good enough for us to get going; however, there is a better class that we can extend and that is the Game class.

What is so special about this class? Essentially, it is ApplicationListener that delegates the game to a screen. Every bar method, such as onCreate(), is implemented. This will save us lots of time going forward.

The following code is the Game class from the LibGDX framework:

public abstract class Game implements ApplicationListener {
  protected Screen screen;

  @Override
  public void dispose () {
    if (screen != null) screen.hide();
  }

  @Override
  public...
Left arrow icon Right arrow icon

Description

LibGDX is a cross-platform game development framework in Java that makes game programming easier and fun to do. It currently supports Windows, Linux, Mac OS X, Android, and HTML5. With a vast feature set on offer, there isn't a game that can’t be made using libGDX. It allows you to write your code once and deploy it to multiple platforms without modification. With cross-platform delivery at its heart, a game can be made to target the major markets quickly and cost effectively. This book starts with a simple game through which the game update cycle is explained, including loading textures onto your screen, moving them around, and responding to input. From there you’ll move on to more advanced concepts such as creating a formal game structure with a menu screen, adding a game screen and loading screen, sprite sheets, and animations. You’ll explore how to introduce a font to optimize text, and with the help of a game that you’ll create, you’ll familiarise yourself with the 2D tile map API to create worlds that scroll as the characters move. In the final sample game of the book, you’ll implement a basic version of an Angry Birds clone, which will allow you to use the physic library box2D that libGDX provides access to. An overview of exporting games to different platforms is then provided. Finally, you will discover how to integrate third-party services into games and take a sneak peak at the Social Media API to get a basic understanding of how it fits into the libGDX ecosystem.

Who is this book for?

This book is intended for those who wish to learn the concepts of game development using libGDX. An understanding of Java and other programming languages would definitely be helpful, although it is not a must.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 26, 2015
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281440
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 26, 2015
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281440
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
LibGDX Game Development By Example
€36.99
Mastering LibGDX Game Development
€41.99
Learning LibGDX Game Development- Second Edition
€41.99
Total 120.97 Stars icon

Table of Contents

12 Chapters
1. Getting to Know LibGDX Chevron down icon Chevron up icon
2. Let's Get These Snakes Out of This Book! Chevron down icon Chevron up icon
3. Making That Snake Slick Chevron down icon Chevron up icon
4. What the Flap Is the Hype About? Chevron down icon Chevron up icon
5. Making Your Bird More Flightworthy Chevron down icon Chevron up icon
6. Onto the Next Platform...Game Chevron down icon Chevron up icon
7. Extending the Platform Chevron down icon Chevron up icon
8. Why Are All the Birds Angry? Chevron down icon Chevron up icon
9. Even Angrier Birds! Chevron down icon Chevron up icon
10. Exporting Our Games to the Platforms Chevron down icon Chevron up icon
11. Third-party Services Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(15 Ratings)
5 star 53.3%
4 star 6.7%
3 star 26.7%
2 star 13.3%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




R. Rose Sep 10, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have been looking for a book on Libgdx for a while and when I saw the author mention this on twitter I thought I would give it a go. Libgdx is a cross platform game engine, which is really rather good. The book starts with an example of building a simple snake game, illustrating the mechanics of the game and how to utilise Libgdx. Personally I would have preferred a more basic version of snake, however this is not to the detriment of the book.The second example game, is what make the book for me. It is another version of flappy bird (flappee bee) and again the author gets into the mechanics of the game exceedingly well. This section is a step up in challenge from the previous snake game, however it is paced at the right level. I personally prefer the incremental approach which allows you to build your skills whilst gaining valuable feedback on your code.The final game is a platformer and again building upon the information previously attained, an incremental body of knowledge is used to illuminate a fascinating process of building a working game.Finally I must commend the author on the content, the book is very easy to read (a couple of typos) and I really enjoyed the examples.
Amazon Verified review Amazon
Michelle and Tim Sep 11, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
LibGDX has quickly become the darling of the cross-platform game development world for those ideas that need a bit more power than HTML5 and mobile wrappers can provide. The issue with most books I have found is not actually in the books, but in LibGDX itself. It has been moving and evolving so fast that many of the books on the market today are already outdated. They either use the old project setup method, which is much more difficult and not recommended or the text is so out of date the instructions are worthless.But with word in the LibGDX community that the codebase is stabilizing, this new book fits the bill very well. Going through the initial setup, the pictures and instructions matched-up perfectly, and hopefully will for a long time now that the work flow is more mature. I had no problem setting up my environment at all following this book, and I was also happy to see the author using Jetbrains IDEs (although you can still use Eclipse, and the author describes how).One of the main things I enjoyed about this book is the multi-game style. Most game dev books are in one of two camps: build one larger game through the whole book, or several smaller games. I tend to prefer the latter, since you get to see more varied solutions to a wide variety of problems. It also allows the author to mold each game around the topic being discussed. The only downside is that you have a bit of boilerplate setup for each game before you can tackle the star topic, but the author does re-use code from earlier chapters, and the code is of course available for download if you don't want to keep going through the setup each time.An important distinction that potential readers would probably want to know up-front is that most of the book assumes deployment to desktop platforms. There is a nice treatment near the end that discusses porting to mobile devices, so you aren't left out in the cold, but it will take a bit of self-guided research to completely convert all the games in the book to mobile format (mostly centering around touch input and mobile design itself). Since most developers are likely coming to LibGDX to learn mobile development, that is kind of surprising, but I did not feel the need to remove a star since this book will still get you 95% of the way there. Learning the core of LibGDX is the largest hurdle, and this book fits that bill nicely.In conclusion, I highly recommend this book for learning the basics of LibGDX. It is a fairly short, easy read that still tackles a ton of topics. You may still need a bit of outside research if your aim is mobile game development, but you will have the foundation to do that. Plus, every other book on LibGDX is woefully outdated save for Packt's other book on the topic, "Learning LibGDX Game Development, 2nd Edition". I would still rather choose this book, though, because it is a faster, easier read that will get you at your keyboard working on your own games faster. However, the true scholars among us may want to read this book cover-to-cover first and then grab Learning LibGDX 2nd Ed and pick through some of the chapters on more advanced topics and cross-platform mobile development. You would really be prepared for anything following that path!
Amazon Verified review Amazon
Dan Sep 24, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an excellent way to learn how to build your own games. The fact that the games can be exported to most platforms is what makes LibGDX so good.The book gets straight intoteaching you how to make games through a few great examples; this make it easy for you to then move on and create your own concepts.if you're looking to learn how to build your own games, this is the book to go for. Both beginners and novice developers should find this book useful.
Amazon Verified review Amazon
Raja Biswas Jan 13, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Best LibGDX game development book. This is the only book that starts from beginning and show you everything that you need to do to build fully functional games. This book shows how to build Complete games like Snake, Flappy bird, Platformer, Angry Birds and more. The step by step approach of the writer is very easy to follow. Loved it. :)
Amazon Verified review Amazon
iPaul Dec 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good intro book to LibGDX, starts with a simple game (Snake) example and expands this in the next chapters.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.