Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
29. June 2016


Welcome to a new tutorial series here on 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.




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 
        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 
        public void lightChanged(){
            System.Console.WriteLine("Light Changed");
            //  For each state, move to the next appropriate state.  I.e, red 
            becomes green, etc. 
                case States.Green:
                _state = States.Yellow;

                case States.Yellow:
                _state = States.Red;

                case States.Red:
                _state = States.Green;

            // Reset our timer, so this will all happen again and again

            // Call our event.  This is used to communicate with the outside 
            world that our state change occured

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

        // these two work together to provide the callback functionality
        // Implementing callback is going to differ greatly from langauge to 
        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); };

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

15. March 2016


Nevigo have updated and changed the pricing for articy:draft, including a new subscription pricing option.  articy:draft can be thought of as a project management and design solution specifically for game development, a sort of mashup between MS Project and Viseo, but geared towards game

Details on the new subscription model called FLEX pricing:

Finally the time has come: We roll out the FLEX license subscription model for all versions of articy:draft. This new license eliminates the initial costs of using articy:draft and gives you maximum flexibility to scale your team up and down. It is an additional licensing option, the purchase option is still available as well.

  • Use articy:draft for a low monthly rate
  • Subscriptions may be cancelled monthly
  • Purchased and rented licenses can be mixed
  • All updates and upgrades included

Additionally they have made changes to the existing licensing model:

We did some spring cleaning to our pricing model to make it easier and more transparent. The different server tiers and upgrade costs are gone, and the core products all come at the same price. Effectively, this leads to a price drop in many cases, especially when scaling up your previously “indie”-sized studio.

  • One price for articy:draft, the API and articy:access
  • Floating licenses available
  • Unified shop experience for single and multi user
  • Simplified costs when adding more licenses

They also added some hosting services and training options.  Full details are available here.

GameDev News Design

8. March 2016


A new version of the popular open source Tiled Map Editor was released today, Tiled 0.15.2.  Unless you happen to be Portuguese or Turkish (who received new translations in this update), there isn’t really a ton new in this release:


This small patch release ships with added Turkish translation and an updated Brazilian Portuguese translation! There are also some fixes, though they are more on the cosmetic side.

  • Added Turkish translation (by Nuri Uzunoğlu)
  • Fixed hiding of object labels when deleting an object layer
  • Fixed updating of object label colors when changing object types
  • TMX: Added image size attributes to image layer images
  • Updated Brazilian Portuguese translation (by Laete Meireles)

The Tiled page3 has been updated with the new download links.

In the meantime, many features have been added on the development branch during January and February. And since editing of external tilesets1 is becoming a huge change, I plan to make a Tiled 0.16 release available in the coming weeks, so stay tuned!


If you are interested in learning more about Tiled, we have done an in-depth tutorial series here on GameFromScratch, that should get you up and running with ease.

GameDev News Design

19. January 2016


A few weeks back I looked at creating Isographic tiles in Blender.  Today we are going to follow it up with a tutorial on creating Orthographic tiles instead.  Orthographic and isometric simply refer to the camera’s projection mode.  In an orthographic project, the camera is straight on and the image does not become smaller as it gets further away from the camera.  Most traditional top down or side view tiles, such as Metroid or Mario Brothers, are orthographic.


Blender gives you a bunch of advantages when creating tiles, especially when it comes to auto-tile support.  You can see auto tiling in action in our Tiled Map Editor tutorial series.  By creating a sequence with the proper border between varying tile types, the auto tile algorithm can figure out the rest.  In this tutorial we will show how to setup Blender so creating these transitions becomes trivial.


There is also a video version of this tutorial available here or embedded below.


First fire up Blender.  Because we are rendering everything in the end, it’s critical we set the dimensions properly.  In this case I am going to try and keep all of my tiles to 2x2 Blender units.  With the 3d cursor at 0,0,0 add a new plane, the default location is ideal:



Now switch to edit mode, then UV unwrap it.  This is going to hold our texture.  I am going to use a pair of seamless textures I created for roads, one a straight section, the other an intersection:


The important part of these textures is they are (relatively) seamless.  I accomplished this by cloning the edge of the one corner of the intersection, then pasting it over the 3 other edges of the intersection, then the two ends of the straight piece.  It’s not flawless, but it’s close.


Now, in object mode, apply the texture to the plane.  We will start with the intersection.  Create a new material if one does not exist, then switch to the texture tab and add the texture to the diffuse channel.  If you don’t know how to do this, check out one of our existing Blender tutorials, they will teach you everything you need to proceed.


The end result should now look like this:



Woot, half way there... well, a quarter...  Now render this and you should see...



Well, that’s not ideal...  two problems here... first our lighting, second, our transparent region is being rendered.  First lets fix the lighting.  When creating tiles you probably want a flat lighting.  First select the scenes default light and delete it.  Now, with no lights in the scene, we want to turn Ambient Occlusion on.  In the properties, locate the World setting then enable AO, like so:



Now when we render:



Much better.  Now we just have to sort the whole transparency thing.  Select your plane, then go to the material tab and enable transparency, then set Alpha to 0, like so:



Now switch to the texture, check alpha and set the value to 1:






Perfect!  We are now at least half way there...  now lets create another tile, this one for the road.  Once again with the cursor at 0,0,0 create another plan, then move it by 2 units ( G, Y, 2 )


Now repeat the above process, just using the other texture instead, and our end result should look like:



Cool!  The only catch you might run into is you may have to rotate the UV 90 degrees to get the road to line up properly with the intersection. 


Now is where the magic of working in Blender can kick in... making our background.  Now create yet another plane object, this one 1wide, 2 high.  Most importantly, move it down the z axis a little bit, so the result should look something like this:



Now texture this new object however you wish... create your sand layer, grass layer, whatever.  Here it is with a quick grass texture applied:



Now we need to set up our camera.  There are two approaches we can take here... we can out camera to capture our entire image then split the tiles up using a tool like Imagemagick, or we can render each tile manually.  The choice is up to you. 


First switch your camera into Orthographic mode, with the camera selected, select the camera tab, then Orthographic:



The following settings are going to be determined by the number of tiles you have and the resolution of your map.  I will use the above example, and I want to render each plane out to 4 (2x2) tiles so our over all image is 4x2.  I am going to render out to a single image and split the tiles later.  To do this, first I went to the camera settings, and set the resolution like this:



I positioned the camera like this:



And set the camera properties accordingly:



With the Blender view in Ortho mode (5 on numpad), it should look like:



Now render, and:



Finally I fire up the following Imagemagick command to split the image into tiles.  As my rendered image is 1024x512, I am going to break it into 256x256 tiles:

convert -crop 256x256 tilesheet.png tiles%d.png

And now we should have 8 very game ready tiles:



Very cool.


Now, thanks to the fact we are in 3d using Blender, we can simply change the background texture and create instead a desert background say...



Five seconds later, a new autotilable texture transition!

Video Version

Art Design

13. January 2016


Welcome to the final part of our three part series on level creation using Blender.  In the first part of the tutorial we created a skybox for our world.  In the second we used a height map to create some terrain.  Today we are going to look at applying multiple textures to that terrain.


We are going to pick up where we left off, we have a large plane distorted to create our landscape.  If you haven’t already, apply the Displace modifier to make it permanent.  You should have already UV Unwrapped the plane object before we applied the displace modifier, giving us a nice even UV grid to work with.


Next we are going to need some textures to paint with.  Seamless textures work best as they can be tiled without creating a noticeable seam.  For this example however, I just downloaded a couple textures from TextureLib, a grass, rock and water texture.  Use whatever textures you wish to use.  Now that you have your textures, we need to import them into Blender.  I find the easiest way is to just add them as textures to the plane object and name them appropriately, like so:


No need to setup mapping coordinates or anything else, as we arent going to be using these textures directly, they just needed to be made available for Blender.


Now with your Plane selected, make sure there is a Material, and if there isn’t, create a new one.



Now switch over to the texture tab and add a new texture of type Image or Movie, then click the New button:



Call in GroundTexture or something similar:



You may find 1024x1024 is too low res for a large terrain, so you might want to try 2048x2048.  Now it’s time to start painting our texture.  Configure your Blender windows so you have a 3D view on one side and the UV/Image Editor on the other, and switch the 3D view to Texture Paint mode, like so:



Now in the UV editor, make sure that your GroundTexture is active:



In the 3D view, in the Tools (T) sidebar, we now set the texture we want to paint with.  Locate the texture area, click the thumbnail icon and select one of your textures, like so:



Now we can paint directly on the 3D model.  You have a ton of control over your brush, but the two most important settings are these:



These set the size of your brush and the strength of your paint tool.  Now simply paint the terrain as you desire:



You will notice that the texture updated automatically the the UV/Image Editor:



If you prefer, you can edit in the UV editor window instead, simply turn Edit mode on:



The brush settings from the 3D View Tools window will be applied to the UV editor in Paint mode.  Now simply change textures and repeat the process until your texture is complete.  When you are done, you may want to export your texture for use in an external engine.  In the UV/Image Editor, select Image->Save As Image:



End result:



Not the greatest looking level, but that’s due to lack of effort, not the tool.  Not bad for 20 minutes work.  Obviously there are other tasks you’d want to perform.  You probably want a normal or displacement map on the terrain to give it small surface level imperfections, and obviously you’d want to add static meshes for trees, shrubs etc... but that is simply a matter of doing more of the same.


The Video

Art Design

AppGameKit Studio

See More Tutorials on!

Month List