Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

24. July 2016


Traditionally I don’t recommend beginners start with C++.  There are a number of reasons behind this opinion, most of which are explained in this video.  Most of the reasons however have very little to do with the language itself (which does of course have some downsides) and more to do with the build system, linker and limited included libraries.  I recently discovered a library aimed at beginners that alleviates a great deal of the downsides of learning using C++, raylib.  It’s free, open source (available on Github) and provides most of the functionality you require to make a game.  Most importantly, it’s aimed at beginners meaning the library is easy to use and comes with a turn key installer that enables you to hit the ground running.

If you are interested in learning more about raylib, be sure to watch this video (also embedded below).


The key features of raylib are:

- Written in plain C code (C99)
- Uses C# PascalCase/camelCase notation
- Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0)
- Unique OpenGL abstraction layer (usable as standalone module): [rlgl]
- Powerful fonts module with SpriteFonts support (XNA fonts, AngelCode fonts, TTF)
- Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC)
- Basic 3d support for Geometrics, Models, Heightmaps and Billboards
- Materials (diffuse, normal, specular) and Lighting (point, directional, spot)
- Shaders support, including Model shaders and Postprocessing shaders
- Powerful math module for Vector and Matrix operations [raymath]
- Audio loading and playing with streaming support (WAV, OGG, XM, MOD)
- VR stereo rendering support with configurable HMD device parameters
- Multiplatform support: Android, Raspberry Pi, HTML5, Oculus Rift CV1
- Custom color palette for fancy visuals on raywhite background
- Minimal external dependencies (GLFW3, OpenGL, OpenAL)


The part I found most impressive though is the installer.  It comes with a pre-configured version of the MingW compiler and Notepad++ set up for development right away.  Basically you run the installer, open notepad++, start writing code and hit F6 to run it.  No dealing with setting up a compiler, learning about linkers and all the various things that make the C++ learning curve so painful.  Well, most of the things...


I should point out quickly, while I’ve been calling it a C++ library, it’s actually a C library.  This is a minor distinction as it is perfectly usable in C++ and feels like C++.  It comes with a copious amount of examples, with very easy to understand code.  Here for example is an, um, example that illustrates loading and drawing images:

*   raylib [textures] example - Image loading and drawing on it
*   NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU 
memory (VRAM)
*   This example has been created using raylib 1.4 (
*   raylib is licensed under an unmodified zlib/libpng license (View raylib.h 
for details)
*   Copyright (c) 2016 Ramon Santamaria (@raysan5)

#include "raylib.h"

int main()
    // Initialization
    int screenWidth = 800;
    int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [textures] example - image 

    // NOTE: Textures MUST be loaded after Window initialization (OpenGL context 
    is required)

    Image cat = LoadImage("resources/cat.png");             // Load image in CPU 
    memory (RAM)
    ImageCrop(&cat, (Rectangle){ 100, 10, 280, 380 });      // Crop an image 
    ImageFlipHorizontal(&cat);                              // Flip cropped 
    image horizontally
    ImageResize(&cat, 150, 200);                            // Resize flipped-
    cropped image
    Image parrots = LoadImage("resources/parrots.png");     // Load image in CPU 
    memory (RAM)
    // Draw one image over the other with a scaling of 1.5f
    ImageDraw(&parrots, cat, (Rectangle){ 0, 0, cat.width, cat.height }, (
    Rectangle){ 30, 40, cat.width*1.5f, cat.height*1.5f });
    ImageCrop(&parrots, (Rectangle){ 0, 50, parrots.width, parrots.height - 100 }
    ); // Crop resulting image
    UnloadImage(cat);       // Unload image from RAM

    Texture2D texture = LoadTextureFromImage(parrots);      // Image converted 
    to texture, uploaded to GPU memory (VRAM)
    UnloadImage(parrots);   // Once image has been converted to texture and 
    uploaded to VRAM, it can be unloaded from RAM

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
        // Update
        // TODO: Update your variables here

        // Draw


            DrawTexture(texture, screenWidth/2 - texture.width/2, screenHeight/2 
            - texture.height/2 - 40, WHITE);
            DrawRectangleLines(screenWidth/2 - texture.width/2, screenHeight/2 - 
            texture.height/2 - 40, texture.width, texture.height, DARKGRAY);

            DrawText("We are drawing only one texture from various images 
            composed!", 240, 350, 10, DARKGRAY);
            DrawText("Source images have been cropped, scaled, flipped and 
            copied one over the other.", 190, 370, 10, DARKGRAY);


    // De-Initialization
    UnloadTexture(texture);       // Texture unloading

    CloseWindow();                // Close window and OpenGL context

    return 0;


All examples are a single .c file and there are plenty of them.  All you need to do is open them in Notepad++ and hit F6 to run.


At the end of the day, I still don’t personally think C++ is the ideal language to learn game programming, or programming in general.  However if you are going to start using C++, raylib is the single best starting point I have ever seen.  In fact, let me know if you would be interested in a beginner C++ tutorial series built around this library, let me know!


The Video


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



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



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.



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. 



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



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:



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



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.



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:



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



In the Add Component dialog, choose Sprite.



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



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.



Next select the Walk animation we defined earlier.


Now your game object Sprite will show in Collection.



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



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:



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

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 using a Google account.  First head on over to and click the Get Defold button.



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:



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



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.



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



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:



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.



A list of available projects should now be available.



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.



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



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



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



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



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:



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



Clicking Team enables you to add users to your project:



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:



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:



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() {
		var tiles = new Array<Tile>();
		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:


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.



Now the code:

	override function init() {
		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() {

		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


Month List

Popular Comments