LibGDX Video Tutorial: Hello World!

18. November 2014


In this video tutorial, we create our first LibGDX project.  This tutorial covers that basic layout of a LibGDX application, adding new assets to a project and looks at how the initial project is composed and how multiple platforms are supported.  We then go through the initial code, then look in depth at coordinate systems, then move on to creating a sprite.  Finally we look at positioning, scaling and rotating a sprite with a SpriteBatch.


This tutorial assumes you already have your development environment setup and know how to run a LibGDX application in your chosen IDE.  If you do no, please watch these videos first.


The following is the video tutorial.  It was recorded in 1080p and the complete version can be viewed here.



The following is the final code generated:


package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;

public class HelloWorld extends ApplicationAdapter {
   SpriteBatch batch;
   Texture img;
   Sprite sprite;
   public void create () {
      batch = new SpriteBatch();
      img = new Texture("HelloWorld.png");
      sprite = new Sprite(img);
   - sprite.getWidth()/2,
   - sprite.getHeight()/2);

   public void render () {, 0, 0, 1);;
      batch.draw(sprite, sprite.getX(),sprite.getY(),sprite.getWidth()/2,


Here is the image that was used in this tutorial:


Programming , , ,

Adventures in Phaser with TypeScript -- Mixing 2D and 3D Graphics using Phaser and Three.js

16. November 2014



First off, let's start of with a big disclaimer!  This is more of an experiment that worked than a tutorial, as I can’t actually recommend you do anything I just did!  Let’s just say, I did a few really hack worthy things to get this particular example to work.  That said, it does work and the results are cool enough I figured I’d share them.  So, there is the warning…  all the code in this example works, but it might be a really really really bad idea! ;)


Ok, disclaimer covered…  now on to what we are actually going to cover, using a 3D model in Phaser.  Out of the box Phaser doesn’t actually have any support for 3D, but Three.js certainly does.  So what we are going to do is use Three.js to load a model and render it to a canvas, which then can be used as the image source for a Phaser Sprite.  If you’ve got no prior experience with Three.js I previously did a two part ( part one, part two ) series on Three.js, from which this a lot of this code was copied.


So let’s jump right in with the code.  It’s heavily commented, but doesn’t really explain any Three.js or Phaser specifics, see earlier tutorials for that.  We are going to render a threejs scene to a canvas, and then use that canvas as a sprite.  In this example, the Threejs scene will be visible, while in real life you would set it to invisible.



<!DOCTYPE html>

<html lang="en">
    <meta charset="utf-8" />
    <title>Model rendered in ThreeJS and used in Phaser</title>
    <script src=""></script>
    <script src="phaser.js"></script>
    <script src="Main.js"></script>
<h1>Model rendered in ThreeJS and used in Phaser</h1>
<table width="600">
        <th>Canvas rendered in Phaser</th>
        <th>ThreeJS rendered to Canvas</th>
        <td width="300px" align="center"><div style="width:298px;height:298px;" id="content"></div></td>
        <td width="300px" align="center">
            <div id="hiddenContent" style="width:298px;height:298px;visibility:visible;"></div>



///<reference path="./three.d.ts"/>
/// <reference path="phaser.d.ts"/>

module Test {

    export class RunningState extends Phaser.State {

        // Create the Threejs variables we need

        // Create the Phaser variables

        // This flag indicates our model is loaded and ready to be poked and proded
        goTime:boolean = false;

        constructor() {

            // ThreeJS setup
            this.renderer = new THREE.WebGLRenderer({ alpha: true });

            this.renderer.setSize(256, 256);
            this.renderer.setClearColor(0x0000FF, 1);
            // ThreeJS renders to a (normally) hidden canvas in the hiddenContent div
            // In real life you'd set it's visiblity to false

            // Create the scene and a camera
            this.scene = new THREE.Scene();
            this.threeJSCamera = new THREE.PerspectiveCamera(75
                , 1
                , 0.1, 1000);

            this.threeJSCamera.position = new THREE.Vector3(0, 0, 1.5);

            // Like framebuffers, the results are upside down once rendered.
            // As I couldn't find a way to flip UVs in PIXI, I instead render the scene upside down
            // by rotating the camera 180 degrees on Z axis

        create() {
            // Set this because we want to display FPS details
   = true;

            // Load the model exported from Blender in threejs format
            // Model loads async
            var modelLoader = new THREE.JSONLoader();
            var that = this;
            modelLoader.load("model/model.jsm", (geometry, materials) => {

                // This is the callback for when our model is loaded, set everything up here
                this.mesh = new THREE.SkinnedMesh(geometry, new THREE.MeshFaceMaterial(

                this.mesh.position.y -=1; // Center vertically about origin

                // add the loaded mesh and a light to the scene
                that.scene.add(new THREE.AmbientLight(new THREE.Color(1.0, 1.0, 1.0).

                // Start threejs up

                // For some reason, you dont get lighting for a while...
                // This is a gross hack... basically we wait a second and then create a Phaser Sprite
                // and then render the canvas to our sprite.
                setTimeout( () => {
                    that.sprite =, 0, null);
                    // Set goTime flag so we know it's go time baby.
                    that.goTime = true;

        // This is the function that actually call Threejs's render
        // Then we set the Sprite's texture to the canvas
        // Warning, this may be horrible for performance.
        renderThreeJS(target:Phaser.Sprite) {
            if (this.renderer) {
                this.renderer.render(this.scene, this.threeJSCamera);

                if(target) {
                            .children[0], PIXI.scaleModes.DEFAULT));

        // Let's just print out debug framerate
  "FPS" +,0,20);

        // Just so we can see that updates to the ThreeJS scene result in the Sprite being updated
        // We simply rotate by 0.01 radians per frame... note this is running as fast as possible
        // So will rotate differently on different machines...
            if(this.goTime) {

        start() {

    export class SimpleGame{
            // Create a game, and our RunningState, passing true to make it start right away
   = new Phaser.Game(256, 256, Phaser.WEBGL, 'content');

// On window load, create an instance of our SimpleGame
window.onload = () => {
    var three = new Test.SimpleGame();


And the code running:



Now there are a few horrific hacks in this code.  First off, there is a “warm up” in Threejs, where for a few ms, it renders without lighting… no clue why, so I just brute force by delaying for a second after Threejs rendering starts.  The next brutal hack is to get the Phaser texture to show, I destroy the previous version… there HAS to be a better way to do this.  Interestingly, in Chrome the results to the canvas are flipped.  However, on Safari they are not!  The joy of HTML5.


As you can see though, mixing 3D objects in a 2D Phaser game is very much possible and actually fairly easy.




Setting up Java, Android SDK, GWT plus Eclipse or IntelliJ to work with LibGDX–Video Tutorials

12. November 2014


The title pretty much says it all.  The installation process to get a fully working Java, Android and GWT development environment up and running can be a bit tricky at times.  These three videos walk through the entire process, from downloading and installing a Java JDK, then the Android SDK and GWT then finally creating your first LibGDX project.  The second video then looks at working with IntelliJ IDEA with LIbGDX, the third video shows the same thing for Eclipse.  Each of these videos walks through loading a project, then running a Desktop, Android then HTML5 project.  Each of the videos is hosted on YouTube and is available in 1080p.  Click the link above the video below to open it directly in YouTube.


Part 1: Configuring a Java Development Environment for LibGDX and Android Development



Part 2: Using IntelliJ IDEA with LibGDX



Part 3: Using Eclipse with LibGDX


Programming , ,

Libgdx Cross-Platform Game Development Cookbook review

10. November 2014


Up until now, there has been only one book on the market for LibGDX and it’s a bit long in the tooth at this point.  Now there is a new book in town, the Libgdx Cross-Platform Game Development Cookbook and I just finished reading through it.  Let me start by saying, this book wasn’t at all what I was expecting… (how’s that for a hook?).



This book was written by Alberto Cejas Sanchez and David Saltares Marquez, who is the man behind the Ashley ECS component included in LibGDX.  So you can safely the authors know their stuff.  Additionally, one of the editors was Joost van Ham ( also known as Xoppa ), this is the guy that wrote the 3D portions of LibGDX.  So we can say right up front this is a technically competent and accurate book.  Full disclosure, I got a review copy of the book, not that this has any influence.  On a somewhat related note, this book is not yet available on Safari Books online.


If you’ve never read a Packt cookbook series book, the basic premise is it’s a collection of “recipes”, which can be thought of as task oriented code samples coupled with a description.  With a traditional cookbook, say you wanted to cook a Quiche Lorraine ( for whatever aberrant reason! ) you’d flip open the cookbook to the quiche section and follow the recipe.  These cookbooks work very similar, except instead of retched pies it’s got recipes for things like creating a 2D depth of field shader or generating and rendering bitmap fonts. 


Over time, I have read a number of those Packt cookbooks, I’ve even written one and let me tell you right up front, the quality varies massively from book to book.  One of the big flaws with many of these books is the author’s grasp of English, whether it’s that English is their second language, or they simply aren’t great writers.  Fortunately, this is not the case with this book.  The language is clear, the grammar is solid and there were very few errors that I spotted.  Most importantly, language was never a barrier to my understanding what the author was trying to say.  Nothing is more frustrating when trying to learn something than being tripped up by the authors inability to articulate, so this is a big point in the books favour.


Let’s take a quick look at the book’s Table of Contents:


  • Chapter 1: Diving into Libgdx
  • Chapter 2: Working with 2D Graphics
  • Chapter 3: Advanced 2D Graphics
  • Chapter 4: Detecting User Input
  • Chapter 5: Audio and File I/O
  • Chapter 6: Font Rendering
  • Chapter 7: Asset Management
  • Chapter 8: User Interfaces with Scene2D
  • Chapter 9: The 2D Maps API
  • Chapter 10: Rigid Body Physics with Box2D
  • Chapter 11: Third Party Libraries and Extras
  • Chapter 12: Performance and Optimization
  • Chapter 13: Giving Back


The book weights in at 487 pages.  I suppose I should clarify, the Chapter 9 title is very confusing. It covers 2D TileMaps, creating them in Tiled and loading them into LibGDX.  Remember back at the very beginning where I said “this book wasn’t at all what I was expecting”?, well… here’s why...


Looking at that list of topics and you probably come to the same conclusion as me, that this book is going to guide the reader through the process of learning Libgdx in escalating difficulty, frankly much like my own tutorial series does.  You would be wrong though.  To understand why, you need to look into one of these chapters to see what typical recipes look like.  Let’s take Chapter 9 as an example, the chapter on tilemaps, and not just because it’s one of the shortest… ;)


On a chapter on tilemaps, what do you except to see covered?   Creating and loading certainly, but what else?  Maybe something on layers, possibly something on mixing sprites with tilemaps maybe?  Nope, what you get is:

  • Introduction (an overview)
  • Creating maps with Tiled and loading them into Libgdx
  • Adding and querying map metadata
  • Developing your own map loaders and renderers


It’s that last one that defines this book, in my opinion.  I would have never expected to see that topic covered in this book, and I find it shockingly awesome that it is there.  It’s this level of technical detail that really makes this book.


So often these books are written to target beginners, and that makes sense, as they are generally the biggest audience for a book.  In all honesty, and this may sound more conceited then I intend it to be, but I was expecting to personally get nothing out of this book.  I know LibGDX pretty well myself and as an example when I read Learning Libgdx Game Development I don’t believe I learned anything new nor was it ever a source I went back to when I was encountering difficulty.  This of course isn’t a bash on that book, I’m just not the intended audience.


This book however, as an experienced LibGDX developer, represents a new and very useful tool in my toolbox.  It’s technical enough, applied enough and deep enough to be genuinely useful to developers writing real world code.


This however is a double edged sword.  If you are completely new with LibGDX, this may not be the book for you.  You have to absorbed a LOT of information all at once and this isn’t really a book that is set up to teach you from scratch.  For example, instead of teaching the user how to draw a sprite, then rotate and scale it, then deal with it in a resolution independent manner, the first drawing example does it all at once.  Incredibly useful information to an experienced developer… confusing as hell to a beginner.


The breadth of content is pretty solid.  If you are creating a 2D game, chances are what you need to know is covered in here.  There are a few odd decisions (IMHO), such as covering Git usage ( entire books are written on this subject already ), but not covering 3D at all, even though the guy that created the 3D api’s is one of your technical editors! :)  I know what writing to a page budget feels like, so deciding what to include and what not to include is an excruciating process.



So then, what’s my over all conclusion on the Libgdx Cross-Platform Game Development Cookbook?  Well, I don’t give a numeric rating or star score when I review things, but I can summarize it pretty easily with this title.


If you are an experienced developer working with LibGDX, buy this book, it will most certainly be of use to you.  I know my own copy will be dog eared from use! ( well… if digitial copies could get dog eared that is ).

If you are a beginner looking to learn LibGDX, this book will certainly be of use to you, especially as you get more comfortable.  That said, I wouldn’t recommend starting here, this is not a beginners book… fortunately, I know a good set of tutorials to get you up and running! 


So yeah, TL;DR...

Buy this book.

General, Programming

Adventures in Phaser with TypeScript– Physics using Arcade Physics

7. November 2014



I’ve already cheated a few times using physics with the caveat that “I will cover this later”.  Well, welcome to later!  One thing you should be aware of right away is that there are a number of different physics engines available in Phaser.  In this particular tutorial we are going to cover Arcade physics, but there is also P2, Ninja and coming soon as a premium plugin, Box2D.


You may be thinking to yourself… huh?  Why the hell are there 3+ physics engines?   Let me try to break it down as best as I understand it.  First thing to know is, there is zero overhead from all of these systems, you need to enable them before you can use them, so you only pay the costs of what you need.


The Physics systems in Phaser are:

  • Arcade is a light weight engine, not the most accurate or full featured, but fast.  It’s also historically what was in Phaser all along.
  • P2 is an existing Javascript physics library.  It’s far more featured than Arcade, but also a lot slower as there is a ton more calculations going on behind the scenes.
  • Ninja… well Ninja I don’t entirely get the purpose behind.  As best I understand it, the author of Phaser, Richard Davey, wrote it a while ago and ported it from Flash to Phaser.  I think it falls somewhere in between Arcade and P2 in the feature/performance scale.  It’s stripped down in functionality from P2.
  • Box2D, well first off, it’s not available yet.  It is about as close to industry standard as 2D physics systems get though.


You can also use more than one physics system at a time, but they wont interact.  So if you have something either with tons of them in the scene ( say bullets or particles ) or where you need only basic physics, you can use Arcade.  Then if you require more accuracy, use P2.


This particle tutorial is going to look at Arcade Physics.  Let’s start with a very simple example.  We are going to enable physics, turn on gravity and enabled a sprite to be a physics body.

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    player: Phaser.Sprite;

    constructor() { = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:this.preload, render: this.render
    preload() {"decepticon", "decepticon.png");
    render() {
        // This renders debug information about physics bodies;
    create() {
        this.player = / 2, 0, "decepticon");

        // Start the ARCADE Physics system;
        // Enable physics on the player sprite, Phaser.Physics.ARCADE);

        // Set the sprite to collide with the worlds edge
        this.player.body.collideWorldBounds = true;
        // And set bounce in the Y axis ( called restitution in most physics system ) to 1, 
        // which will make it bounce equal to 100 %
        this.player.body.bounce.y = 1;

        // Set the physics engines overall gravity.  98 == 98 pixels per second in this demo = 98;

window.onload = () => {
    var game = new SimpleGame();


Run it:



This example is pretty heavily commented, so I wont go into much detail.  It illustrates a few key concepts.  First, you need to start the physics subsystem before you can use it.  Second, you need to initialize a sprite to be a physics object.  Finally, you can render debug information using game.debug.body(), which will draw the bounding box as seen by the physics engine.  This can be incredibly useful for debugging physics simulation problems.


Now one of the very first things people are going to want to use a physics engine for is collision detection, so lets do that next!

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    player1: Phaser.Sprite;
    player2: Phaser.Sprite;

    constructor() { = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload,
            render: this.render, update: this.update
    preload() {"decepticon", "decepticon.png");
    update() {
        // Now check for a collision between objects, this.player2);
    render() {
    create() {
        this.player1 =, / 2 - 50, "decepticon");
        this.player2 =, / 2 - 50, "decepticon");;

        // You can enable multiple bodies at once by passing in an array like so:[this.player1, this.player2]);
        this.player1.body.collideWorldBounds = true;
        this.player2.body.collideWorldBounds = true;

        // Set the players to bounce along x axis instead
        this.player1.body.bounce.x = 1;
        this.player2.body.bounce.x = 1;

        // Now set them moving.  Move to the center of the screen accelerating to 100pixels per second, / 2,
                                       / 2 - 50, 100);, / 2,
                                       / 2 - 50, 100);
        = 0;

window.onload = () => {
    var game = new SimpleGame();

And the results:


This example shows us a couple things.  Most important is for collisions to occur you need to test for them using collide().  You can also see from this example that it’s possible to initialize multiple physics bodies at once by passing all the sprites in to game.physics.arcade.enable as an array.  This demo also illustrates that you can easily turn gravity off in a simulation.


In this particular demo we used AccelerateToXY to get our bodies moving.  There are a number of other functions for moving physics bodies, checking for intersections, measuring distances and angles available in the Physics.Arcade class, they work fairly straight forward so I leave exploring them as an exercise for the reader.  There are a few final concepts I want to touch on before moving on.


The first is collision handling.  The above example simply tested if a collision happened.  Phaser Arcade physics however give you a great deal more control than that, as will now see.  When you call collide() you have the option of passing in a pair of callbacks, like so:

    update() {
        // Now check for a collision between objects, this.player2,
            // This callback is called when a collision occurs
            // In this example we scale object1 on collision until its 2x bigger in size
            (object1: any, object2: any) => {
                // object1 and object2 will be either of type Sprite, Group, Tilemap or Particle Emitter
                if (object1 instanceof (Phaser.Sprite)) {
                    (<Phaser.Sprite>object1).scale.multiply(1.1, 1.1);
                    if ((<Phaser.Sprite>object1).scale.x > 2) {
                        (<Phaser.Sprite>object1).scale.set(1, 1);
            // This callback is called for additional testing, AKA user driven logic on if a collision occurs
            // If you return true, a collision occured, if you returned false, a collision doesn't occur
            // In this example, object checks the direction in the X axis it's moving, if moving right to left
            // then a collision wont occur.  As a result, the first collision test 
            //both objects will pass through each other.
            (object1: any, object2: any) => {
                if (object1 instanceof (Phaser.Sprite)) {
                    if ((<Phaser.Sprite>object1).deltaX < 0)
                        return false;
                        return true;

Which when run results in:

The code comments explain most of what happens.  Basically you have a pair of callbacks available.  The first one is the action to perform IF a collision occurs, in addition to any action the physics engine is going to take that is.  In this simple example, we scale one of the two colliding objects up until it’s size has doubled.  As you can see, the colliding and collided objects are passed in to this function.  The type of this object can be a Sprite, Group, Particle Emitter or Tilemap.  We actually used Arcade Physics in earlier tilemap and particle tutorials if you want more details on collisions between these types. 


The second callback determines if a collision occurs at all.  Returning false out of that function means that no collision occurred, while true indicates one did.  If you run this example ( click here to open it in a new browser as it’s probably already run too far ), you will notice that on the first pass, no collision occurs.


The final thing I want to touch on is grouping.  As mentioned above, in the collision callbacks, one of the types of collisions that can occur is between groups.  I am not going to go into detail as I already covered grouping earlier, but I wanted you to be aware that you can group sprites together then perform collisions that way.  This is handy when you have a large number of similar sprites, such as bullets, because frankly doing a collide() call for each possible combination get’s old quickly!


In the future I will look at some of the other physics systems, but for quick and dirty collisions and simple physics, Arcade Physics should be enough.


Programming , ,