Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

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

8. November 2014


Amber have just open sourced Copperlicht, a WebGL 3D JavaScript engine.  Copperlich was previously available for 99 Euro per year.



Here is an overview of Copperlicht’s functionality:

  • 3D World editor: CopperLicht comes with a full 3D world editor named CopperCube.
  • Many supported 3D file formats: 3ds, obj, x, lwo, b3d, csm, dae, dmf, oct, irrmesh, ms3d, my3D, mesh, lmts, bsp, md2, stl, ase, ply, dxf, cob, scn and more
  • Built-in Collision detection: Throw a polygon soup into the engine and walk around the 3D world.
  • Lots of 3D graphics features, see below.
  • Incredibly fast: CopperLicht is highly optimized and able to render and animate even huge 3d scenes.
  • Character/Skeletal animation: supports playing back animated meshes with an unlimited amount of joints and an unlimted amount of weights
  • Simple to use: easily understandable SceneGraph API with lots of tutorials and examples in the documentation
  • Binary compilation: Unlike other WebGL 3D Engines, CopperLicht compiles your 3D meshes into a small, binary file which downloads quickly, reducing bandwith usage for your users. Simply import your 3D files into the CopperCube editor and publish it as CopperLicht scene.
  • Totally free: CopperLicht is free to use. And open source. Just download and go!


You may notice the strike through that Copperlicht includes a 3D world editor; this isn’t entirely true with the open sourced version.  There is a commercial editor available named CopperCube, however it is a commercial product


I have to say, I like this move.  You can create a full game using Copperlicht without the editor, while the editor is available on a 14 day trial.  This means people can contribute to a Copperlicht project without paying money, but there is a value add sell that means the developer can eat!  I hope this will result in an increase in popularity for Copperlicht that in turn increases sales for Coppercube, which would be win/win.  I personally would like to see the demo extended to 30 days, or preferably be 14 actual days, not 14 calendar days.


This announcement is quite timely, as I just recently had this conversation on Twitter:




I feel almost prescient!


This is a slightly different business model, but one I firmly support.  On the whole I think this is a great change.  I have used Irrlicht in the past and was impressed by the engine.  Now I am going to look closer at Copperlight and possibly due a tutorial series on it in the future.  Now that Copperlicht and Coppercube are a bit less intwined, I wonder if Coppercube could move to being more agnostic and be of use to say… Three.js or Turbulenz.


Are you at all interested in hearing more about the Copperlicht engine here on GameFromScratch?

News , ,

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 , ,

6. November 2014


I will admit, I am somewhat late to this party… I’ve shared a project or two to Github in the past, but I’ve never really embraced it.  It’s one of those things I should probably change and I will start to address. 


So here we are starting with the code samples for the TypeScript with Phaser series.  For many tutorials I often didn’t keep the solutions I used to create examples, so I have nothing to share.  However for this series, I have done all of the work in a single Visual Studio solution, so it made pushing it up to Github easy.  You will find 90% of the examples from that series are now available on Github.  For a few minor samples, I simply made changes to the base project to come up with the derived code, so you wont find those ones.  I pushed everything up, so that means all the assets used are included too.  Since I continue to use this single solution for the entire project, as I add new examples, they will be available on Github as well.


You can access all the samples here on Github.




I will be the first to admit, I know very little about Github as anything other than a consumer, so expect so tales of epic stupid while I get the hang of things.  Right now there are 29 projects in the PhaserTypescript repository, although PhaserArcade is a WIP ( guess what I’m working on… ).


Let me know if I’ve made any mistakes here. Hope this code proves useful to somebody.

Programming , ,

5. November 2014


One of the challenges of working on the iPad only is the lack of animation and composition tools.  There are tons of art applications out there as we saw earlier, but nothing for getting them into game ready form.  So I had a bit of an idea and ran with it.


The basic idea is I am using iDraw to create individual body parts, which I then add to shape libraries so I can see how it will look all put together.  My game is going to be giant robots, so I can take a mix and match approach to character composition.  By building out the characters from parts, I can then create a variety of characters using minimal art.  Here is the process in iDraw:



The problem is, when I export the end result into Codea, I don’t have something that I can use.  I would have to export each frame of animation for each mech combination one by one from iDraw to Codea to get an animated resulted, which ruins almost all of the benefits.


So, essentially, what I have to do, at least initially, is reproduce this functionality in Codea, so I can then create animations and variations without a massive increase in body parts.  So that is exactly what I did.  In a second you are going to see massive walls of code that I used to accomplish the task.  First I should make a few things clear.


The biggest one is, this is one of those things I am doing for fun, so most of this code was written during intermission between hockey periods, while waiting for something or while falling asleep in bed.  On the one hand, it’s really really cool that you can code at those times.  On the other hand… code quality tends to suffer a bit.


The next is along the same lines.  Lua is one of those languages that encourages experimentation… and a language that I haven’t used in a while.  A lot of times I got something to work and refactored later, if at all.  So if you see some things that make you aghast… that is probably why! :)  I am by no means done… at this point I’ve mostly just replicated the functioning above, I still intend to add several features before the tool is usable.  First and foremost I need to keyframe animations.  I added the controls, just no logic.  Of course I also need to save the results so they can be used in another game.  On top I want to polish the functionality by adding parenting, different control modes ( selection, parenting, positioning, animating ).  That all said, you do see the skeleton of a genuinely useful tool written entirely in Lua on an iPad.


This is VectorPoser




The code, although rather ugly and in need of refactoring, is pretty well commented, so it should require minimal explanation… I hope.


Main.lua This is the application entry point.  Most of the touch logic is currently handled here, but should slowly be moved out


-- VectorPoser

-- welcome to the league of evil globals
imageList = nil  -- The image selector down the side of the screen
cachedWidth = WIDTH -- The original width, used to check if screen width changes
character = nil -- The character you are working on
selectedPart = nil -- The currently selected part of the character, if any
animationControl = nil -- Functionality, coming soon, stay tuned!

-- Use this function to perform your initial setup
function setup()
    local files = spriteList("Dropbox")
    local vectors = {}
    for k,v in pairs(files) do
        table.insert(vectors,readImage("Dropbox:" .. v))
    imageList = ImageList(WIDTH-100,HEIGHT,100,HEIGHT,vectors)
    character = Character(WIDTH/2,HEIGHT/2)
    animationControl = AnimationControl(60,0)

-- This function gets called once every frame
function draw()
    background(40, 40, 50)
    update()  -- put all non rendered updates in a single function so we can eventually decouple
              -- updating from the rendor loop, maybe, someday, I promise. Maybe.
    -- This sets the line thickness in pixels I think
    -- render our image list, which again is the list of images down the right hand side
    -- now draw our VCR style animation controls
    -- clip our viewport so it wont draw in the same space as the image list
    -- now draw our character

function touched(touch)
    -- pass along touches to all the touchables so they can be touched, duh!

    -- TODO, spin the following code out to a function or class so we can have different 
    -- touch handling in different modes 
    -- Check to see if there is a currently selected part
    if selectedPart then
       -- if something is already selected, continue until touch up 
        if(touch.state == ENDED or touch.state == BEGAN) then
            -- If the touch ended or paradoxally began, unselect the active part and trigger 
            -- changed so UI updates
            selectedPart = nil
            -- otherwise move the selected part to the touched location
            selectedPart.x = touch.x
            selectedPart.y = touch.y
            -- now update so parameters get updated
        -- There is no currently selected part, check if this touch hits an existing part
        local hits = character:getPartsAtPoint(touch.x,touch.y)

        if #hits > 0 then
            -- find the highest z value and make it selected
            -- yes, this makes touches items behind other items a pain in the ass
            for i,v in pairs(hits) do
                if selectedPart == nil then selectedPart = v
                    if v.z > selectedPart.z then
                        selectedPart = z
            -- Notify UI of the change
    -- if you swipe the right edge right, hide the ui off the screen to the right
    -- on swipe left nring it back on screen
    -- TODO: Move logic into the ImageList
    if touch.x > WIDTH-100 then
      -- clear selection if user clicks off main area
          selectedPart = nil
        if touch.deltaX < -20 then
            --left swipe
            local x,y = imageList:getPosition()
            if x == WIDTH then
        if touch.deltaX > 20 then
                -- right swipe
        -- otherwise lets clear selected if touched anywhere else
        local img = imageList:getSelected()
        if img then


-- handle all non graphical updates on a per frame basis
function update()

-- called when device is changed from landscape to portrait and vice versa
-- we need to resize our ImageList
function orientationChanged(orientation)
    if imageList then

-- there may be a better way to do this, but check for a change in size, specifically
-- due to parameters windows going away and coming back causing a resize
function checkResize()
    if cachedWidth ~= WIDTH then
        -- resize occured, handle accordingly
        cachedWidth = WIDTH
        -- TODO: This currently brings hidden panel back on screen... probably shouldn't
        imageList:setPosition(WIDTH -100,HEIGHT)

-- when the selected part changes update params
function selectedPartChanged()
    if selectedPart == nil then
        -- z axis changed
        parameter.integer("Z order",0,20,selectedPart.z,
        function(val) selectedPart.z = val end)
        -- delete button, remove selected part from character
        function(val) selectedPart.rotation = val end)


ImageList.lua This is the control down the right hand side that enables you to select images.  It handles scrolling up and down, as well as flick left to hide flick right to show.  Most of the logic is in displaying the images and mapping from touch to selected image.

-- imagelist is for displaying a number of images for selection
-- supports scrolling via long drag up and down

ImageList = class()

function ImageList:init(x,y,width,height,imgs)
    -- you can accept and set parameters here
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.imgs = imgs
    self.IMAGE_HEIGHT = 100
    self.maxVisibleImages = math.floor(self.height/self.IMAGE_HEIGHT)
    self.topImageIndex = 0
    self.selected = nil
    self.touchDeltaY = 0

function ImageList:draw()

function ImageList:touched(touch)
    if self:_isTouchInFrame(touch) then
        if touch.state == ENDED then
            self.touchDeltaY = 0
        -- as the user swipes up or down within the imagelist track the y delta
        -- if it exceeds 50 increase or decrease the topImageIndex
        -- thus scrolling the available images
        if touch.state == MOVING then
            self.touchDeltaY = self.touchDeltaY + touch.deltaY
            if self.touchDeltaY > 50 then
                if self.topImageIndex + self.maxVisibleImages <= #self.imgs then
                    self.topImageIndex = self.topImageIndex + 1
                self.touchDeltaY = 0
            if self.touchDeltaY < -50 then
                if self.topImageIndex > 0 then
                    self.topImageIndex = self.topImageIndex - 1
                self.touchDeltaY = 0


-- draw a frame around our control
function ImageList:_drawFrame()
    stroke(13, 0, 255, 255)
    line(self.x,self.y,self.x + self.width, self.y)

-- draw the visible images within our control
function ImageList:_drawImages()
    local currentY = 0
    for i= self.topImageIndex,self.topImageIndex+self.maxVisibleImages do
        local curImage = self.imgs[i]
        if curImage then
            local aspect = curImage.width/curImage.height
            if aspect < 1 then -- taller than wide
            sprite(curImage,self.x +self.width/2,self.y-currentY-self.IMAGE_HEIGHT/2,self.width * aspect
,self.IMAGE_HEIGHT) else -- when its wider than tall, shrink it proportionally local newHeight = self.IMAGE_HEIGHT * aspect - self.IMAGE_HEIGHT sprite(curImage,self.x +self.width/2,self.y -currentY-self.IMAGE_HEIGHT/2,self.width,
newHeight) end currentY = currentY + self.IMAGE_HEIGHT end end end -- draw a line above and below selected image function ImageList:_drawSelection() if self.selected then rectMode(CORNER) strokeWidth(2) stroke(255, 16, 0, 255) local x = self.x local y = self.y - (self.selected -1)* self.IMAGE_HEIGHT fill(255, 4, 0, 255) line(x+5,y,x+self.width-5,y) line(x+ 5,y-self.IMAGE_HEIGHT,x + self.width-5, y-self.IMAGE_HEIGHT) end end -- convert to local coordinates and figure out which item is selected at touch position function ImageList:_touchToSelected(touch) -- convert touch relative to top left of screen if self:_isTouchInFrame(touch) then -- local localX = touch.x - self.x local localY = self.y - touch.y local offset =math.ceil(localY/self.IMAGE_HEIGHT) if offset <= #self.imgs then self.selected = offset else -- self.selected = nil end end end -- check if touch within the bounds of our control function ImageList:_isTouchInFrame(touch) if touch.x >= self.x and touch.x <= self.x + self.width and touch.y <= self.y and touch.y >= self.y - self.height then return true end return false end function ImageList:setPosition(x,y) self.x = x self.y = y end -- handle resize, mostly for orrientation change function ImageList:setDimensions(width,height) self.width = width self.height = height self.maxVisibleImages = math.floor(self.height/self.IMAGE_HEIGHT) end function ImageList:getPosition() return self.x,self.y end -- gets the index into the img array of the selected image function ImageList:getSelectedIndex() if self.selected then -- hack for foggy brain -- if self.topImageIndex > 1 then self.topImageIndex = self.topImageIndex - 1 end return self.selected + self.topImageIndex end return nil end function ImageList:clearSelected() self.selected = nil end -- gets the actual image function ImageList:getSelected() return self.imgs[self:getSelectedIndex()] end


Character.lua -- This holds the character we are creating. Mostly just a collection of VectorPart now, but more functionality will be coming in the future

-- a character is composed of several VectorParts.
-- this will ultimately be the class you use to control everything as a single entity
-- AKA, the end result

Character = class()

function Character:init(x,y)
    -- you can accept and set parameters here
    self.x = x
    self.y = y = {}

function Character:draw()
    -- order drawing by z order
        function comp(a,b)
            if a.z < b.z then return true end
            return false

    for i,v in ipairs( do

function Character:touched(touch)

function Character:addPart(part)
     part.z = +1 -- z order equal order added initially

function Character:removePart(part)
    if(part) then

function Character:getPartsAtPoint(x,y)
    local results = {}
    for i,v in pairs( do
        if x >= v.x - v.img.width/2 and x <= v.x + v.img.width/2 and
            y >= v.y - v.img.height/2 and y <= v.y + v.img.height/2 then
            v.curIndex = i
    return results

function Character:getParts()


VectorPart.lua -- These are the individual parts, right now it's just the image, x,y and rotational data, but in the future it will have pivot and parenting information. Keyframe data will essentially be a snapshot of these values per animation frame

-- A vector part is simply the vector img, plus positional and rotation data
-- will be adding parenting information

VectorPart = class()

function VectorPart:init(img,x,y,z)
    -- you can accept and set parameters here
    self.img = img
    self.x = x
    self.y = y
    self.z = z
    self.rotation = 0
    self.curIndex = nil

function VectorPart:draw()

function VectorPart:touched(touch)


AnimationControl.lua -- This is a VCR style keyframe animation control, mostly just a placeholder for now

AnimationControl = class()

function AnimationControl:init(x,y)
    self.x = x
    self.y = y
    self.buttonFirst = IconButton("First",x+0,y+0,64,64,"Documents:IconFirst","","")
    self.buttonFirst.callback = _firstButtonPressed
    self.buttonPrevious = IconButton("Previous",x+66,y+0,64,64,"Documents:IconPrevious","","")
    self.buttonPrevious.callback = _previousButtonPressed
    self.buttonPlay = IconButton("Play",x+66*2,0,64,64,"Documents:IconPlay","","")
    self.buttonPlay.callback = _playButtonPressed
    self.buttonNext = IconButton("Next",x+66*3,y+0,64,64,"Documents:IconNext","","")
    self.buttonNext.callback = _nextButtonPressed
    self.buttonLast = IconButton("Last",x+66*4,y+0,64,64,"Documents:IconLast","","")
    self.buttonLast.callback = _lastButtonPressed

function AnimationControl:draw()

function AnimationControl:touched(touch)
    -- Codea does not automatically call this method

function _firstButtonPressed()
function _previousButtonPressed()
function _playButtonPressed()
function _nextButtonPressed()
function _lastButtonPressed()


Finally I used a library called Cider for the UI controls. You can get Cider here. I used the IconButton class, but it didn't have callback support, so I hacked it in like so:

--# IconButton
IconButton = class(Control)

-- IconButton 
-- ver. 7.0
-- a simple control that centers an image in a frame
-- ====================

function IconButton:init(s, x, y, w, h, img, topText, bottomText)
    Control.init(self, s, x, y, w, h)
    self.controlName = "IconButton"
    self.background = color(255, 255, 255, 255)
    self.font = "HelveticaNeue-UltraLight"
    self.fontSize = 32
    self.img = img
    self.text = s
    self.topText = topText
    self.bottomText = bottomText
    self.textAlign = CENTER
    self.smallFontSize = 12

function IconButton:draw()
    local h, w
    w, h = textSize(self.text)
    fontSize(self. smallFontSize)
    w, h = textSize(self.topText)
    text(self.topText, self:midX(), self:top() - h / 2 - 4)
    if self.bottomText then
        text(self.bottomText, self:midX(), self:bottom() + h/2 + 4)
    if self.img == nil then
        text(self.text, self:midX(), self:midY())
        sprite(self.img, self:midX(), self:midY())

function IconButton:initString(ctlName)
    return "IconButton('"..self.text.."', " ..
        self.x..", "..self.y..", "..
        self.w..", "..self.h..", '"..
        self.img .. "', '"..
        self.topText .. "', '"..
        self.bottomText .. "', '"..

-- added by mjf... not sure why there wasnt a touch handler on this control
function IconButton:touched(touch)
        if self:ptIn(touch) then
            if touch.state == ENDED then
                if self.callback ~= nil then self.callback() end
                return true


There is some bugginess around the selectedPart handling that leads to the occasional crash, and I am on occasion crashing Codea if I use lots of images, but for the most parts, it's the skeleton of a downright usable tool. It's never going to compete with the likes of Spline or Spriter, but it should suffice for making game ready models and animations from sprite and vector graphics and at the end of the day, that's all I need. Stay tuned for an update sometime in the future.


Month List

Popular Comments

Creating a spritesheet using Daz Studio and The GIMP
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

Home > Art >

13. February 2012



I have been playing around a bit with Daz 3D Studio since it was recently made freely available. At first I struggled to find an actual use for the program, then I realized how exceptionally easy it made creating animated sprites. The following tutorial will walk through creating the following walk cycle using Daz Studio:

The above image is actually a web animation generated from this spritesheet that we will create. All told, the process will take about 5-10 minutes, most of it will be you waiting for your computer!  If the above image isn’t animating, that means your browser ( most likely Internet Explorer ) doesn’t support the keyframes CSS attribute.  Trust me, it works. Smile



You are going to need a couple things to follow along this tutorial, all of which are (currently) freely available.


You will need:




Install all of these products.  Now we fire up Daz Studio.


We are going to use the default human, feel free to drag and drop and design your guy however you want.  That said, do not move the person from the default screen location.


Once your guy or gal is dressed/decorated however you want, its time to add some animations.  On the left hand panel, select Content Library, Walks then start-(N) and drag it down to the beginning of the timeline.


Like so:




If done correctly, if you press play your character will now have a walk cycle.  You can drag down as many animations as you would like to capture, just add them one after another in the timeline.  In this example we are just going to do the single walk cycle animation.


Now comes the key part, you don’t actually want your character to be moving like it does currently, you want him to remain stationary.  First lets frame things into the left.  Click the view selector box to rotate to the left view.



This is the guy you are looking for, click the red section labeled left.  Now ideally your window should look something like this:





Now we need to strip out the movement part from the animation.  To do so, first we need to convert to Studio keyframes.  This is done by right clicking in the blank gray area above the timeline and selecting Bake to Studio Keyframes, like so:




You will get the following message:




Simply click Yes.  Now we can edit out your animation.  What we want to do is remove movement along the Z-axis.  In order to do this, select Parameters along the right hand panel, then you want to select the Hip ( the root of all animations ).  You can do this by either clicking it within the scene Window, or selecting it from this drop down:





Now that you have the Hip selected, in the Parameters panel ALT+Left click the zTranslate panel:



This process should reset it’s value to 0.  Now if you press play on the timeline, your animation should now be stationary.  Now its time to render our images out.  To do so in the menu select Render->Render Settings…  like so:




The following window will appear:




If not already done, make sure at the bottom right it is set to “Show Advanced Settings”.  Now drag the quality/speed slider down to 3 ( or it will take forever, for little visible gain ).  Now you want to scroll the options down a bit.  First we want to set our image render resolution.  I personally went with 128x96, but you can use whatever you want.





Now scroll the options down a bit more and select the Render To: drop down.  You want to select Image Series like this:




Now we want to select where to render it to.  Leave Start and End Frame at the defaults ( the entire animation ), file in a name and leave it as PNG so we get transparencies.  Switch the location from Library to Folder and pick a directory you want it to save your renderings to, like so:



Now click the green “Render” button.  You will get a warning like the following:



Simply click OK.


Now we wait… there is absolutely no indication it’s actually doing anything, but Daz Studio is now rendering your sprites.  The only real indicator it’s doing anything is the spinning “busy” mouse icon.  Let it do it’s thing, it took approximately 4 minutes on my PC.


Once it is completed, in Explorer navigate to the directory you told it to render to.  If all went well, your directory should be populated with 51 PNG images.  Here’s mine:





Now that we have our sprites, we need to make them into a sprite sheet.  If you haven’t already, install The GIMP and the sprite sheet plugin I linked earlier.  Now load up The Gimp.


In GIMP select File->Open As Layers…



Navigate to the folder you saved your images to, then CTRL+A to select them all ( or CTRL + Click to select them one by one ).  When finished press Open:



If everything worked correctly, your layers list should look like this:




Now select the Filters Menu->Sprite-Sheet->Create From Layers…  If this menu option doesn’t show up, you haven’t installed the spritesheet plugin correctly.




Gimp will now merge all of the layers together into a single sprite sheet in a new window like so:





Simply save this file and you are done.  My end results are this.  You may want to do some editing, like making your spritesheet square instead of one wide and short image, but this can be accomplished in a few minutes of copy and paste.  All told, one remarkably fast way to generate a walk cycle sprite animation.  Rendering other angles or different animations is simply a matter of repeating the process from a different angle or dragging and dropping different animation sets.


Of course, you can also create your own animations quite simply in Daz.  You can also import your own meshes and props, although I haven’t really experienced this part yet, so I do not know how painful the process is. 

Art , ,

blog comments powered by Disqus

Month List

Popular Comments