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?).

Gdxcover

 

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.

 

Summary


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() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
    }
    render() {
        // This renders debug information about physics bodies
        this.game.debug.body(this.player);
    }
    create() {
        this.player = this.game.add.sprite(this.game.width / 2, 0, "decepticon");

        // Start the ARCADE Physics system
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        
        // Enable physics on the player sprite
        this.game.physics.enable(this.player, 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
        this.game.physics.arcade.gravity.y = 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() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload,
            render: this.render, update: this.update
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
    }
    update() {
        // Now check for a collision between objects
        this.game.physics.arcade.collide(this.player1, this.player2);
    }
    render() {
    
    }
    create() {
        this.player1 = this.game.add.sprite(this.game.width, this.game.height / 2 - 50, "decepticon");
        this.player2 = this.game.add.sprite(0, this.game.height / 2 - 50, "decepticon");

        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        // You can enable multiple bodies at once by passing in an array like so:
        this.game.physics.arcade.enable([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
        this.game.physics.arcade.accelerateToXY(this.player1, this.game.width / 2,
                                                this.game.height / 2 - 50, 100);
        this.game.physics.arcade.accelerateToXY(this.player2, this.game.width / 2,
                                                this.game.height / 2 - 50, 100);
        
        this.game.physics.arcade.gravity.y = 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.game.physics.arcade.collide(this.player1, 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;
                    else
                        return true;
                    }
            },
            this);
    }

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




Phaser with TypeScript code samples published to Github

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.

 

image

 

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




Creating a Game on an iPad -- Building an Animation Tool in Codea Part 1

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:

IDrawAssembly

 

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

 

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))
    end
    
    imageList = ImageList(WIDTH-100,HEIGHT,100,HEIGHT,vectors)
    character = Character(WIDTH/2,HEIGHT/2)
    
    animationControl = AnimationControl(60,0)
end

-- 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
    strokeWidth(5)
    
    -- render our image list, which again is the list of images down the right hand side
    imageList:draw()
    
    -- now draw our VCR style animation controls
    animationControl:draw()
    
    -- clip our viewport so it wont draw in the same space as the image list
    clip(0,0,imageList:getPosition())
    
    -- now draw our character
    character:draw()
end

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

    -- 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
            selectedPartChanged()
        else
            -- otherwise move the selected part to the touched location
            selectedPart.x = touch.x
            selectedPart.y = touch.y
            
            -- now update so parameters get updated
            selectedPartChanged()
        end
    else
        -- 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
                else
                    if v.z > selectedPart.z then
                        selectedPart = z
                    end
                 end
            end
            -- Notify UI of the change
            selectedPartChanged()
        end
    end
    
    -- 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
                imageList:setPosition(WIDTH-100,HEIGHT)
            end
            end
        if touch.deltaX > 20 then
                -- right swipe
                imageList:setPosition(WIDTH,HEIGHT)
        end
    else
        -- otherwise lets clear selected if touched anywhere else
        local img = imageList:getSelected()
     
        if img then
            character:addPart(VectorPart(img,touch.x,touch.y))
         end
        
        imageList:clearSelected()
    end
    

end

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

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

-- 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)
    end
end

-- when the selected part changes update params
function selectedPartChanged()
    if selectedPart == nil then
        parameter.clear()
    else
        -- z axis changed
        parameter.integer("Z order",0,20,selectedPart.z,
        function(val) selectedPart.z = val end)
        
        -- delete button, remove selected part from character
        parameter.action("Delete",function()
            character:removePart(selectedPart)
            selectedPartChanged()
        end)
        
        parameter.number("Rotation",0,360,selectedPart.rotation,
        function(val) selectedPart.rotation = val end)
    end
    
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
end

function ImageList:draw()
        self:_drawFrame()
        self:_drawImages()
        self:_drawSelection()
end

function ImageList:touched(touch)
    self:_touchToSelected(touch)
    if self:_isTouchInFrame(touch) then
        if touch.state == ENDED then
            self.touchDeltaY = 0
        end
        
        -- 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
                end
                self.touchDeltaY = 0
            end
            
            if self.touchDeltaY < -50 then
                if self.topImageIndex > 0 then
                    self.topImageIndex = self.topImageIndex - 1
                end
                self.touchDeltaY = 0
            end
        end
    end
end



    

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

-- 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
    self.parts = {}
end

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

    table.sort(self.parts,comp)
    
    for i,v in ipairs(self.parts) do
        v:draw()
    end
end

function Character:touched(touch)
end

function Character:addPart(part)
     part.z = #self.parts +1 -- z order equal order added initially
    table.insert(self.parts,part)
end

function Character:removePart(part)
    if(part) then
        table.remove(self.parts,part.curIndex)
    end
end

function Character:getPartsAtPoint(x,y)
    local results = {}
    for i,v in pairs(self.parts) 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
            table.insert(results,v)
        end
    end
    return results
end

function Character:getParts()
    return self.parts
end

 

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
end

function VectorPart:draw()
    pushMatrix()
    translate(self.x,self.y)
    rotate(self.rotation)
    sprite(self.img,0,0)
    popMatrix()
end

function VectorPart:touched(touch)
end

 

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
    
    
end

function AnimationControl:draw()
    self.buttonFirst:draw()
    self.buttonPrevious:draw()
    self.buttonPlay:draw()
    self.buttonNext:draw()
    self.buttonLast:draw()
end

function AnimationControl:touched(touch)
    -- Codea does not automatically call this method
    self.buttonFirst:touched(touch)
    self.buttonPrevious:touched(touch)
    self.buttonPlay:touched(touch)
    self.buttonNext:touched(touch)
    self.buttonLast:touched(touch)
    
    
end

function _firstButtonPressed()
    
end
function _previousButtonPressed()
    print"fhdhdj"
end
function _playButtonPressed()
    
end
function _nextButtonPressed()
    
end
function _lastButtonPressed()
    
end

 

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
end

function IconButton:draw()
    local h, w
    w, h = textSize(self.text)
    pushStyle()
    fill(self.foreground)
    stroke(self.foreground)
    self:roundRect(4)
    fill(self.background)
    stroke(self.background)
    self:inset(1,1)
    self:roundRect(4)
    self:inset(-1,-1)
    font(self.font)
    fontSize(self. smallFontSize)
    textMode(CENTER)
    textAlign(CENTER)
    smooth()
    w, h = textSize(self.topText)
    fill(self.textColor)
    text(self.topText, self:midX(), self:top() - h / 2 - 4)
    if self.bottomText then
        text(self.bottomText, self:midX(), self:bottom() + h/2 + 4)
    end
    if self.img == nil then
        fontSize(self.fontSize)
        text(self.text, self:midX(), self:midY())
    else
        sprite(self.img, self:midX(), self:midY())
    end
    
    popStyle()
end

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

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

 

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.

Programming




LibGDX Tutorial Part 15: Particles Part One–2D Particles

3. November 2014

 

 

Now we are going to look at using particles in LibGDX.  This is a somewhat complex subject, so I am going to break it over a couple posts.  In this first example, we are going to create a 2D particle system in the editor.  Then we are going to write the code to run the particle system.  This process can be somewhat confusing, especially running the Particle Editor, so I have also done a video version of this tutorial.  Don’t worry, I will always continue to do text versions of all LibGDX tutorials, I am just going to mix in video when I think it will help.

 

So if you prefer, this topic is available in the video below.  Click directly on Youtube to see it in full resolution.  Once again, this video covers exactly the same content the text below does.

 

In this tutorial we are going to use one of the tutorials included with LibGDX, the particle editor.  In order to follow along you need to install the gdx-tools in your project.  Fortunately this is a pretty easy process.  When you run the setup utility to create your project, make sure you set tools to true.

 

image

 

This will result in the particle editor being included in your project dependencies.  Now it’s a matter of running the ParticleEditor, which isn’t as obvious as you would think.

 

You can run it from the command line, but this presents a certain special challenge, since LibGDX moved to a Gradle based setup…  so, where exactly is gdx.jar these days?  That’s a good question, and the answer is very very well hidden.

 

First make sure you’ve built your project at least once, so then all of the dependencies have been resolved ( AKA, Gradle downloaded LibGDX ).  Now LibGDX will be located somewhere in your Maven repository, which is a hidden folder.  The actual directory it will be in is random thanks to a GUID key.  On my computer on Windows its:

C:\Users\Mike\.gradle\caches\modules-2\files-2.1\com.badlogicgames.gdx\gdx-tools\1.4.1\SOMEREALLYLONGGUID

 

Obviously on your computer this will be somewhere else, and it will change with each version.  Now that you located it, you can run it.  Fortunately there is a much easier option for running the particle editor if you use either Eclipse or IntelliJ IDEA.  I will cover each in turn below ( and also show both in the video above ):

 

IntelliJ

 

Once you’ve loaded your project into IntelliJ IDEA.  Now in your Projects window, locate gdx-tools.jar ( there will be a version number too, currently 1.4.1 ).

 

image

 

Expand it until you find particleeditor, then locate the class ParticleEditor.

 

Now right click ParticleEditor and select Run ParticleEditor… main():

 

image

 

The first time you need to set some configuration values:

image

 

Really, all you need to do is set the Use classpath value to your desktop module.  Now click Run:

image

 

One working Particle Editor.

 

Eclipse

 

Eclipse is actually much simpler… if it works, which is a big if.

Simply import your project.  Then right click your desktop project, select Run As or Debug As->Java Application.

 

image

 

It should now prompt you to select which Java Application to run:

image

Select ParticleEditor – com.badlogic.gdx.tools.particleeditor and click OK.

The Particle Editor will now load.

 

Your First Particle Effect

 

Now that you’ve got the particle editor open, let’s save an effect to work with. 

In this particular tutorial we are just going to go with the default as it is already configured, which is a flame looking effect.  Locate and click the save button:

image

We want to save the resulting file to our assets folder.  If you have an Android project it will be located at [project]/android-proj/assets otherwise it will be in [project]core-proj/assets.  Save the file there, the extension doesn’t matter.  For this code example I am using particles.party.

 

Code Time

 

Now let’s take a look at the code required to display this effect:

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class Particles extends ApplicationAdapter {
   SpriteBatch batch;
   ParticleEffect pe;

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

      pe = new ParticleEffect();
      pe.load(Gdx.files.internal("Particles.party"),Gdx.files.internal(""));
      pe.getEmitters().first().setPosition(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
      pe.start();
   }

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

      pe.update(Gdx.graphics.getDeltaTime());
      batch.begin();
      pe.draw(batch);
      batch.end();
      if (pe.isComplete())
         pe.reset();
   }
}

 

When you run this app you should see:

 

Results

 

It’s pretty consistent with the way most other systems work in Android.  You create the ParticleEffect then load it from file at the root of your assets folder.  We then position the emitter at the center of the screen.  Particle emitters are the source of particles and are often used to control over all behavior.  We then start the particle system running.

 

In render, just like with physics systems, we need to advance the particle effect using update().  This causes the simulation to calculation the position, colour, etc… of all the particles it controls.  Next we draw the ParticleEffect using draw() and drawing to our sprite batch.   Finally we check to see if the effect is complete, and if it is, we restart it.

 

Obviously we glossed over the Particle Editor tool, as well as 3D particle effects, so expect more tutorials soon.

 

Programming ,