Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

14. July 2016

 

In the previous tutorial we looked at the basics of creating an application using the Defold engine, part of that included the built in Atlas type for displaying a sprite.  In this tutorial we are going to look further into sprites.  In case you are unaware, a sprite is simply a 2D graphic with position and is pretty fundamental to modern 2D games, even if sprites are actually faked in 3D.

 

There is an HD video version of this tutorial here.

 

In the previous tutorial we started with an Atlas created for us.  This time we are going to create one from scratch.  Don’t worry, it’s easy.  So what exactly is an Atlas?  It’s simply a collection of images in a single source.  The Defold engine itself is resposible for determining the ideal layout for the best performance.

 

Creating and Populating an Atlas

 

Creating an Atlas is simple.  In the Project Explorer, right click the folder you want to create the Atlas in and select New->Atlas File

image

 

Next name your Atlas file.  In this case I’m going with walker.  The extension is predictably enough .atlas.  Then click Finish.

image

 

Now we need some Image files to put in our Atlas.  In this case I am using a selection of images I created earlier but you can use whatever images you want.  If you are a Patreon backer, they are available in the Patreon Dropbox in the folder Art\AnimatedCharacter\Spritesheets\Raw\walk.  Whatever images you go with, simply drag and drop them to the images folder inside the main folder.  If you don’t have such a folder, simply right click and create one.

GIF

 

Now make sure Walker.Atlas is open in the editor, then go over to the Outline view, right click Atlas and select Add Animation Group. 

image

 

In the properties window, name the animation walk and set the default playback mode to Loop Forward.

image

 

Now right click the newly created Walk animation group and select Add Images.  In the popup dialog, select all our newly added images.  You can use CTRL or SHIFT to multiselect:

image

 

You will see that Defold automatically arranges all of our frames of animation together into a single atlas:

image

 

Be sure to save your Atlas before continuing.  You can preview the animation by right clicking “walk” in the Outline then choosing Play/Stop Animation.

GIF2

 

Creating a Sprite

Now that we’ve got our populated Atlas and a walk animation, how do we use it?  We create a Sprite.

To do so open up your main level .collection file.  In Outline right click Collection then choose Add Game Object:

image

 

I personally changed the ID of mine to walker.  Now right click the newly created game object and select Add Component.

image

 

In the Add Component dialog, choose Sprite.

image

 

With the sprite selected in Outline, we now need to define some properties, specifically Image and Default animation.

image

 

For Image, it will bring up a dialog box, select our recently created Atlas.  If the Atlas isnt shown, make sure everything has been saved.

image

 

Next select the Walk animation we defined earlier.

 

Now your game object Sprite will show in Collection.

image

 

In this case our sprite is centered about the atlas.  You can move the sprite using the W key.  ( E and R can be used for rotation and scaling as well ).

image

 

Each arrow represents the axis it will be moved along.  Or you can position your mouse inside the square and move freely in any direction.  Position your character then run your game (Ctrl + B) and you should see:

GIF3

 

Creating a Tile Source

You can also use a tile source instead of an Atlas.  A tile source is simply a grid of sprites already arranged into a single image.  To use a tile source instead of selecting Atlas, you select Tile source.  I wont be covering it in detail here ( I will cover tile sources later when we get to tile maps ), but if you want more details check the video where I did cover it.

 

You can also programmatically program the animation, get callbacks when animations complete, etc... but that requires knowledge of message passing... and that’s in the next tutorial!

 

The Video

Programming ,

29. June 2016

 

Welcome to a new tutorial series here on GameFromScratch.com where we will be looking at core concepts of game programming.  This includes data structures, design patterns and algorithms commonly used in game development.  We start the series off with Finite State Machines.

 

There is an HD video version of this tutorial available here and embedded below.

 

What is a Finite State Machine?

 

A Finite State Machine (or FSM for short) is one of those concepts that sounds much scarier than it actually is.  In the simplest form it’s a datatype that can have only one value (state) from a finite selection of values(states).  The easiest way is to understand the finite state machine is to look at a real world example.

 

trafficLight

 

Yep, a traffic light is a perfect example of a FSM, or at least, the logic controlling it is.  Consider the three possible states this particular traffic light can be in.  At any given point (assuming I suppose the power is working...) the light will be one of three states, red, yellow or green.  It can never been more than one of those states at a time, it’s always red or yellow or green.  These are the two keep concepts of a finite state machine.  There are a finite number of states ( 3 in this case ) and only one is true or active at a time.

 

It’s a very simple concept, but extremely useful in game development.

 

What are FSMs Used For?

 

In game development, one of the most common uses for finite state machines is artificial intelligence.  Consider the example of PacMan’s ghosts.  A state machine can be used to control how they behave.  A ghost may have one of several different operating modes for example waiting to be released, hunting, hunted and dead.  The state machine is what is used to drive the ghost’s actions and to switch between states.  You will find AI examples absolutely loaded with state machines, often with some fuzzy logic controlling the transition between states to give a layer of unpredictability to your characters.

AI isn’t the only place of course, think of all the different things in a game that are related, there are multiple different states they can be in, but only one can be active at a time.  Game states are a very common example, where you break your game up into a series of states, for example Loading, Main Menu, Playing, High Score, Exiting.  Many game engines ( one such example is Phaser ) split your game up into a series of states.  The ultimate controller of these states is a finite state machine.  A sequential UI ( think of a sequence of dialogs controlled by next/back buttons ) can also be implemented using FSMs.  They are also commonly used to control elements in a games world.  Consider a game with a weather system, be it day or night cycles or season cycles like Spring, Summer, etc...  these would most likely be controlled via FSMs.

 

Implementing a Finite State Machine

 

The example we are going to use here is to implement a traffic light via FSM.  At it’s core the data is going to be stored in an enum, a natural fit for state machines, but stack based or array based options are also viable.  This example is not only going to switch the traffic lights periodically, it’s also going to implement callbacks so the world at large can interact with the light.  This example is implemented using C#, but should be easily adapted to most modern programming languages.

 

using System;

namespace GameFromScratchDemo
{

    public class TrafficLight{
        // This enum represents the three possible values our state machine can 
        be
        public enum States { Green, Yellow, Red };    
        // This is the amount of time for the timer to wait before changing 
        between states
        private const int LIGHT_DURATION = 5000;

        // An actual instance of our enum.
        private States _state;

        // The timer object that is going to be used to switch between states 
        private System.Threading.Timer _timer;

        // This function is called by the timer when it's time for a light to 
        change
        public void lightChanged(){
            System.Console.WriteLine("Light Changed");
            
            //  For each state, move to the next appropriate state.  I.e, red 
            becomes green, etc. 
            switch(_state){
                case States.Green:
                _state = States.Yellow;
                break;

                case States.Yellow:
                _state = States.Red;
                break;

                case States.Red:
                _state = States.Green;
                break;
            }

            // Reset our timer, so this will all happen again and again
            _timer.Change(LIGHT_DURATION,System.Threading.Timeout.Infinite);

            // Call our event.  This is used to communicate with the outside 
            world that our state change occured
            onStateChange(_state);
        }

        // In our constructor we simply set out default state (green) and 
        create/start our timer
        public TrafficLight() {
            _state = States.Green;
            System.Console.WriteLine("Light Created with initial Green state");

            _timer = new System.Threading.Timer( _ => lightChanged(), null, 
            LIGHT_DURATION,
                System.Threading.Timeout.Infinite);
        }

        // these two work together to provide the callback functionality
        // Implementing callback is going to differ greatly from langauge to 
        language
        public delegate void StateChangedResult(States newState);
        public event StateChangedResult onStateChange;
    }

    // Our actual program.  Simply create a traffic light instance
    // Register a callback that will simply print the current state returned 
    when the light state changes
    // And finally wait for the user to hit enter before ending the program
    public class Program
    {
        public static void Main(string[] args)
        {
            TrafficLight light = new TrafficLight();
            light.onStateChange += (TrafficLight.States state) => { Console.
            WriteLine(state); };
            Console.ReadLine();
        }
       
    }
}

The example is pretty well documented in the code above.  Essentially we are creating a class TrafficLight that can internally have one of three states Green, Yellow or Red.  It also implements a timer that switches between those states.  To make the code actually useful, it also implements a callback system so code external to the TrafficLight can interact with it as a black box.  The callback will be passed the current state value every time the light changes.

 

This is obviously a simple example of a state machine but the same basic premise remains regardless to complexity.  It is a very useful data structure for organizing code, especially the flow of logic.  Coupled with callbacks, it is also a great way of keeping systems decoupled as much as possible.

 

The Video

Programming, Design , ,

22. June 2016

 

Welcome to a new tutorial series covering the Defold engine, recently released for free use by King.  You can learn more about the Defold Engine in this video which contains a quick hands on.  It’s a powerful, cross platform Lua powered game engine for 2D game development.  This tutorial series will ultimately walk through all aspects of using the Defold game engine, in both text and video formats.  All of the assets used in creating these tutorials is available on the Patreon dropbox, although I will make source and asset files available as they are needed in text tutorials.  This first tutorial simply walks through getting the Defold engine installed and creating our first project.

 

You can watch the video version of this tutorial here or embedded down below.

 

Getting And Installing Defold Engine

 

Getting started with the Defold engine is very easy, however you will need to log in to Defold.com using a Google account.  First head on over to Defold.com and click the Get Defold button.

image

 

At this point you will have to log in using a Google account.  Once authenticated, you will be redirected to the Defold dashboard.  There are a number of download links available on this page.  Simply pick your appropriate platform:

image

 

This will download an archive file, extract the contents somewhere.

image

 

Defold is run by double clicking the Defold executable.  Before doing so however, let’s create a new project.

 

Creating a New Project in Defold

 

Creating a new Defold project is currently done using the Defold dashboard.  On the left hand sidebar of the dashboard, locate the Add Project button and click it.

image

 

You will now be brought to a very simple configuration form:

image

 

Name your project and click Save.  In my case I am creating a blank project, however Defold have made some sample projects available as a starting point.  If you would rather start there check “Yes, show me your tutorials”.  You will be presented with a list of options:

image

 

Your project is now available.  Let’s load the Editor.  In the folder you extracted Defold, double click the Defold executable.

 

Loading Your Project

 

Now with the editor open, select File->Open Project.

image

 

A list of available projects should now be available.

image

 

Select your newly created project and click Next.  Behind the scenes Defold is creating a git repository for your game.  Since this is the first “checkout”, you need to create a new branch.  Click New Branch then call it V1 or whatever name makes sense to you.

image

 

Defold will now download your project.  Here is the project structure of an empty new project:

image

 

Double click game.project to edit many game specific configuration setting:

image

 

Although our “game” doesn’t actually do anything, you can run it by hitting Ctrl+B or via the Project Menu:

image

 

Certainly not the most exciting game, but it’s a start!

image

 

Managing Your Projects

 

Back in the Defold dashboard, you can edit and delete your projects as well as add additional users.  Your project(s) should now appear on the left hand side of the dashboard, like so:

image

 

Click the gears icon above your project will bring you to the configuration section:

image

 

Clicking Team enables you to add users to your project:

image

 

Of course, they will have to authenticate using Google as well.

 

Finally by clicking Settings you have the ability to change the name and description of your project, as well as delete it entirely:

image

 

Code Hosted on Defold’s Server??? DEALBREAKER!

 

Don’t like the idea of your git repository behind hosted on Defold’s servers?  Well that’s an understandable concern and using the above process, this is exactly what happens.  When you create a project, it’s created as a Git repository on Defold’s servers and when you open it, you are downloading (or more accurately, checking out) to your local server).  It’s understandable that this isn’t for everyone.  Fortunately there is an alternative.

I am not going into details here, but if you want to bypass Defold’s servers complete, follow this guide here.

 

The Video

 

Programming , ,

27. May 2016

 

Welcome back to our ongoing tutorial series on using the Heaps framework with the Haxe programming language.  In the first tutorial we covered the configuration and programming a simple game using Heaps.  Then we covered the basics of 2D graphics in the next tutorial.  In this tutorial we are going to look at using 2D animation in Heaps.  We are going to cover three specific ways, first using a sequence of images for each individual frame of animation, second using a single simple spritesheet image and finally we are going to look at using a texture atlas.  All of the images used in this tutorial are available here, while the project files, source, images etc. are all available to Patreon backers.

 

As always there is a HD video version of this tutorial available here and embedded below.

 

First copy the animation frames into the resource folder.  Each is named along the lines of walk01, walk02, walk03, etc like so:

image

 

Now let’s jump into the code.  The process is almost identical to the sprite handling process from the previous tutorial:

import h2d.Anim;
import h2d.Bitmap;
import h2d.Sprite;
import h2d.Text;
import h2d.Tile;
import hxd.Res;
import hxd.res.Font;

import js.Lib;

import hxd.App;
class Main extends App {
	
	
	var animation:Anim;
	
	override function init() {
		Res.initEmbed();
		var tiles = new Array<Tile>();
		
		tiles.push(Res.walk01.toTile());
		tiles.push(Res.walk02.toTile());
		tiles.push(Res.walk03.toTile());
		tiles.push(Res.walk04.toTile());
		tiles.push(Res.walk05.toTile());
		tiles.push(Res.walk06.toTile());
		tiles.push(Res.walk07.toTile());
		tiles.push(Res.walk08.toTile());
		tiles.push(Res.walk09.toTile());
		tiles.push(Res.walk10.toTile());
		tiles.push(Res.walk11.toTile());
		tiles.push(Res.walk12.toTile());
		tiles.push(Res.walk13.toTile());
		tiles.push(Res.walk14.toTile());
		tiles.push(Res.walk15.toTile());
		tiles.push(Res.walk16.toTile());
		
		animation = new Anim(tiles, 10, s2d);
	}
	
	override function update(dt:Float) {
	}
	
	static function main() {
		new Main();
	}
	
}

 

Here we populate an array of type Tile with all of the images.  Remember Heaps will automatically make available any resource type with an appropriate loader.  Finally we pass this array to the constructor of Anim.  Anim is a special kind of drawable that contains several tiles that represent individual frames of animation.  Also in the constructor we pass along the frame rate to play the animation at, as well as the parent to play the animation relative to, in this case the default scene, s2d.  When you run this code you should see:

GIF

Pretty simple eh?

 

It’s also quite common to want to group all of your sprites together in a single image.  The following example does exactly that using this evenly spaced spritesheet (click for full sized image).  Just be aware, this code requires the width and height of each tile to be the same size.

animation

 

Now the code:

	override function init() {
		Res.initEmbed();
		
		var tileSrc = Res.animation.toTile();
		var tiles = tileSrc.grid(512);
		
		animation = new Anim(tiles, 10, s2d);
		animation.speed = 5;
	}

 

This code has basically the exact same end result.  Basically we load the entire spritesheet into a single tile, then split it into a number of smaller tiles using the grid() method, passing in the dimension to cut by.  Hopefully in the future this function will be updated to take both a width and a height value, removing the square requirement.  As you can see from this example, you can modify the Anim object after the fact, changing the animation speed, it’s position, rotation, scale etc.

 

One final option is to use an Atlas.  An Atlas is basically another form of spritesheet, but instead of being fixed dimensions, it comes with a text description file that says where each frame of animation within the texture is.  This allows you to more tightly store your images in a single image.  In terms of creating an atlas file, two options are LibGDX’s TexturePacker or CodeAndWeb’s TexturePacker.  Of course you could create the file by hand if you preferred.  Now some more code:

	override function init() {
		Res.initEmbed();

		var frame = Res.animationAtlasv1.get("walk01");
		
		var bmp = new Bitmap(frame, s2d);
		bmp.x = 400;
	}

 

As you can see, there is also a loader for Atlas files, so it’s simply a matter of accessing it via the Res interface.  In this particular example we are retrieving a single frame of animation that we use to populate a Bitmap and display on screen.  The Atlas loader also has the option of return an Anim object if preferred.

 

The Video

Programming

17. May 2016

 

In our previous tutorial looking at the Heaps game framework, we looked at creating an initial application.  As part of that tutorial we used s2d to draw some text on the screen.  Today we are going to look a bit closer at using 2D graphics with Heaps.  Let’s start straight off with a simple example:

import h2d.Bitmap;
import h2d.Sprite;
import h2d.Text;
import h2d.Tile;
import hxd.Res;
import hxd.res.Font;

import js.Lib;

import hxd.App;
class Main extends App {
	
	override function init() {
		
		// Example one, create a new Bitmap using a Tile
		Res.initEmbed();
		var logo = Res.logo.toTile();
		var bitmap = new Bitmap(logo, s2d);
		
	}
	
	override function update(dt:Float) {
	}
	
	static function main() {
		new Main();
	}
	
}

 

When we run this example:

image

For this example to work you need to copy an jpg, gif or png file named logo to the resource directory.  Don’t forget you need to tell Haxe where this directory is using the –D resourceDir flag (see previous tutorial for more information ).  In this example we convert the resource to a Tile object, which you can think of as a rectangular region within an image (even if it encompasses the entire image).  Finally we used this tile to create a Bitmap object, which is brings together the thing to draw ( the Tile ) and where to draw it (the Sprite). More on these later.  As before to display it on screen the bitmap is parented to the s2d object, which is a Scene object that is created for us automatically.


Let’s look at another quick source example, the performs a very similar task:

import h2d.Bitmap;
import h2d.Sprite;
import h2d.Text;
import h2d.Tile;
import hxd.Res;
import hxd.res.Font;

import js.Lib;

import hxd.App;
class Main extends App {
	
	override function init() {
		
		// Example two, create a bitmap manually using BitmapData 
		and draw it to screen.
		Res.initEmbed();
		var logoBitmapData = Res.logo.toBitmap();
		var bitmap = Bitmap.create(logoBitmapData);
		s2d.addChild(bitmap);
		
		// Set the pivot point of our bitmap so it is positioned 
		relative to it's center
		bitmap.tile.dx = -Math.round(bitmap.tile.width / 2 );
		bitmap.tile.dy = -Math.round(bitmap.tile.height / 2);
		// Now center the bitmap to the screen
		bitmap.x = s2d.width / 2;
		bitmap.y = s2d.height / 2 ;
	}
	
	override function update(dt:Float) {
	}
	
	static function main() {
		new Main();
	}
	
}

 

And running this one...

image

 

Here we again create a Bitmap to be drawn on screen, but this time using a different process.  In the first example (which is that way you would do things 99% of the time) we loaded the resource as a Tile.  In this example we instead load it using the toBitmap() method.  This is VERY VERY VERY confusing, and is why I decided to show it as an example.  toBitmap() does NOT create a Bitmap object, instead it creates a BitmapData object.  This naming convention was quite poorly chosen in my opinion and leads to a great deal of confusion.  BitmapData can be thought of the raw bytes of information that go together to make all the various pixels in our bitmap.  BitmapData is stored in system memory and is extremely slow to work with.  That said, you can easily manipulate this information, so if for example you wanted to convert all of the individual pixels to grayscale, you could.

Another change here is we didn’t set the Bitmap’s parent (s2d) during construction.  Instead we manually add the newly created bitmap to our scene by calling addChild().  This function will take any Sprite derived class.  We will get back to that in a second, but it’s an important concept to understand.  This second example shows a couple other key concepts.  Notice how we set the position .x and .y?  Well these are simple pixel coordinates to represent where the image should be drawn relative to the origin of it’s parent (s2d in this case).  The origin by default is the top left corner.  In this example we set the pivot point (or origin) by specifying dx and dy.  These are delta values that tell you where drawing calls are made relative to.  In this case we will perform drawing calls on this object relative to it’s mid point.

 

That’s about all I want to cover at this point in time, but there are a few key Heaps classes we should understand before moving on.

 

Sprite

If you come from other game engines, this terminology is very confusing.  Almost universally a Sprite represents and image ( bitmap or texture in memory ) and the position to draw it at.  In heaps however, a Sprite is only about the position of the object. Sprite is the only type of object that can be added to Layer (and thus Scene) ‘s addChild() method call. 

 

Drawable

Drawable inherits from Sprite and is the parent class for things that can actually be drawn on screen.  Bitmap inherits from this class, but so to does Text which we used earlier, as does Anim and Graphics.

 

Scene

s2d is an instance of Scene which is ultimately the root of the 2D scene graph.  At it’s core, Scene is actually a Sprite itself ( via Layer ), but it also holds a special object called Stage and is capable of responding to a number of UI events, as we will see in an upcoming tutorial.

 

Tile

This is another one of those things can be a bit confusing.  A Tile is a rectangle within a texture or image, but ultimately represents a source rectangle that is going to be displayed.  For example, the tile of a bitmap could represent only a portion of the source image.  Consider the following change to our original source:

	override function init() {
		Res.initEmbed();
		var logo = Res.logo.toTile();
		var bitmap = new Bitmap(logo, s2d);
		bitmap.tile.setSize(Math.round(bitmap.tile.width / 2),	
		Math.round(bitmap.tile.height / 2));
	}

 

When this code is run we get:

image

 

The underlying image of our Bitmap is unchanged, but we are only using a quarter of it because we shrank the dimensions of the tile.  This Tile approach is handy when dealing with sprite sheets, where you have several different frames of animation in a single source texture.  We will see this process in a later tutorial.

Programming

Month List

Popular Comments