Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

22. August 2012


SDK is downloaded and installed.  For some bizarre reason, you need to sign up before downloading the SDK ( which… is freely available in source code form on Github… ).  Once you’ve signed up and signed in, head over to and download it.  Personally I am using the August developer snapshot, because apparently, I am crazy like that.  Once downloaded, unzip somewhere, I went with C:\ because I am a lazy lazy man.


So, this is genesis…




Pretty sparse over all.  The docs contain a handful of PDFs, but they appear to be seriously out dated.  MoaiProjectSetup.pdf is certainly worth the read though, it’s got the most technical details that still seem relevant.


For now, I simply care about getting a Windows host working, iOS, Mac and Android can come at a later date.  No sense adding an unnecessary layer of complexity right now.  Moai provides a sample Windows host based around GLUT, you can load the source code for Visual Studio 2010 at C:\moai-sdk\hosts\vs2010.  It has already been compiled at C:\moai-sdk\bin\win32 as Moai.exe.  To make life a bit easier, I am going to add this to my PATH environment variable.  This is completely optional, but I tend to find it makes life easier.  To append MOAI to your PATH environment, from a command run:

setx PATH “%PATH%;c:\moai-sdk\bin\win32”

Oddly enough, permanent environment variable changes do not apply to the current session, so you need to exit and start a new command prompt.  Now you can change into the directory of and run one of the samples.  Let’s try that now, open a command prompt and type:

cd \moai-sdk\samples\hello-moai

moai main.lua


If everything is configured correctly, you should see:



Well, that was easy enough, up and running a sample in about 10 minutes including download times.  Until we actually need to extend the functionality of the client, the default host should be good enough.  You may also noticed, there are .bat and .sh scripts in each example directory if you don’t want to bother setting the path to moai.exe.


Now to give creating a new MOAI project a shot.  Obviously Hello world seems a sensible enough place to start, in fact I believe it is the law.  Therefore we are going to create a simple application that creates a window and displays “Hello World” centered.  Create a new folder somewhere and create a file main.lua in your favorite text editor.  You need to copy a .ttf file named courier.ttf ( or rename it in the code to match ), I simply copied mine from c:\windows\fonts\. Now enter the following code:


MOAISim.openWindow("Hello World", 800,600)

viewport =
viewport:setSize( 800,600)
viewport:setScale( 800,600)

layer =


chars = 'DEHLORW'

font =

text =
text:setString('Hello world')


Basically we:

  • create a window
  • create a viewport for that window, sized at scaled to 800x600
  • create a new layer and set its viewport to the viewport we just created
  • tell Moai we want to render our layer
  • create a series of chars represent the characters in HELLO WORLD
  • create a font loading from the file courier.tff ( which I stole and renamed from c:\windows\fonts )
  • created a MOAITextbox, set it’s text to ‘Hello world’ and font to our newly created font, at 120 font size and 72 DPI
  • we then flip it, as for some bizarre reason, the default text is inverted, and position it in the center of the screen, relative with (0,0) repesenting the middle of the screen, so our dimensions our – 1/2 x,y to + 1/2 x,y
  • finally we tell the text to draw centered vertically and horizontally within the TextBox
  • Finally we add our textbox to our layer with a call to insertProp()


Run it and:



All told, a little complex for a typical Hello World application, but nothing too outrageous.  There are some oddities, like the inverted text, but as you can see, there was also a great deal of control.  Considering this is an application that will run on many platforms, all told, that wasn’t too painful of an experience, was it?



As to the SetYFlip() question, there is an answer of sorts here:

One thing to note about “setYFlip.” While all other props in Moai will automatically assume a world style coordinate, a textbox will assume a window style. To get the textbox to render with world style, you set YFlip to true.

Clear as mud? Winking smile

General ,

21. August 2012


Moai is one of those projects that has been drawing my interest for a very long time.  If you have never heard of it, Moai is an open source,moailogo cross-platform game engine written in C++ but scripted using LUA.  The most obvious comparison that comes to mind is to think of Moai as a free open-sourced Corona but that wouldn’t be completely accurate, for a couple of reasons.


First, well, it is hard to ignore the open source aspect.  With Corona, if you don’t like what you see, tough.  Hopefully they will support what you want in a future release, but if they don’t you are pretty much SOL.  This is certainly a big deal to larger development houses with C++ resources in house.  It is also appealing to me, as if I can’t understand something from the documentation, I can jump into the source code…  speaking of which, that leads to the second point.


Compared to Corona, documentation is sparse to completely non-existent.  Worse still, the community is quite small and there is very little in the way of supporting documentation.  There are a few entry level samples, the documentation on this page and the class reference.  There are no books, few tutorial sites, etc…  Contrasted again against Corona there is this book, plus this and this.  As a technical writer though, this appeals to me.  The less resources that exist on the subject, the more likely people will find what I write! Smile


Another big point is the target audience.  MAOI is written for experienced game developers and targeted at the same demographic.  There is no friendly installer, just a zip to extract.  You have to create a native host for each platform your game is going to run on ( although templates are provided ), and what might take one line in Corona might take ten in Moai.  Why is this?  Moai doesn’t really make decisions for you which is a double edges sword.  On the one hand, it is much more flexible ( infinitely if you include the fact it is open source ) than Corona, on the other hand, it is much more difficult.  To put things in the simplest terms possible, if you have no prior game programming experience and want to make an iPhone game, Moai is probably not right for you.  Don’t get me wrong, I am not implying you can’t make a good game with Moai if you aren’t a pro, much as I am not suggesting you can’t make a professional game with Corona, you obviously can.  Simply put, each SDK targets a different user-base, and Moai targets the group that want to get their hands dirty.  Me, I like to get my hands dirty.


Another big selling point for Moai is the names that have thrown their weight behind it.  It’s rather a whose who of role models. First dblfineoff, is Tim Schafer of Double-Fine Games. Tim’s prior games is a collection of awesome; Psychonauts, Day of the Tentacle, Monkey Island, Full Throttle and even the recent Costume Quest ( which if you haven’t played it, you are missing out ).  Other than making Kickstarter famous, Double Fine’s incredibly well funded upcoming adventure game is being powered by Moai.


Let’s just say, his is a voice that carries a lot of weight.  As does another one, who also reaped the strikeomegabenefits of KickStarter. That would be Harebrained Schemes.  It is possible you’ve never heard of them, as they have only released one game so far, Strikefleet Omega, a very cool RTS for iOS and Android, written of course in Moai.  The fact it is one of the more technically competent games I have played yet on Android speaks well of Moai’s capabilities.  What probably has me most excited though, is the upcoming Shadowrun Returns.  Shadowrun on the Sega Genesis is easily in my top 10 favorite games, perhaps my top 5, so this is a game I am dying to see.  More to the point, it’s the founder of Harebrained Games that really got my attention.  It’s none other than Jordan Weisman.  If there is a template for a successful game designer, this is him.  His past credits include Shadowrun, Battletech, MageKnight, Crimson Skies, Earthdawn and more.


So, Moai has quality published games under it’s belt, the support of heavy weights working on two games I am incredibly interested in ( in a time I am not interested in too many games! ), using a technology ( LUA ), that I have been interested in learning for a very long time ( … like, a decade ).  More so, it is young and growing.


I think it is pretty much a forgone conclusion I *AM* going to be playing with Moai, maybe even working on publishing a game with it, if my schedule allows.  What I want to gauge is, how many you you are interested in Moai?  If I do a series of tutorials, or probably more accurately at first while I am figuring it out, a diary of my progress/experiences, would you be interested?  For now, Moai and LUA will each get their own tag on this site and I will see where it goes from there.

General ,

17. August 2012


In the past I mentioned and even recommended HTML5 developers give WebStorm a shot, this is the IDE I use personally when working in JavaScript, but I realized I never actually said why.  One of the big reasons is, its just a good solid text editor, with good project management and solid code completion, which is an area most tools fail at.  But one of the biggest reasons is, it gives a rock solid debugging experience… very similar to native code.  This is something that can make JavaScript development a WHOLE lot nicer.

EDIT: I should make it clear at this point, virtually nothing in this guide is specific to WebStorm, you can debug using the Chrome Developer Tools or using Firebug in FireFox. Webstorm however integrates the process directly within the IDE.  The process will change slightly ( different buttons/hotkeys ), but the instructions below basically apply to debugging in browser as well.


At the same time it dawned on me… if you don’t come from a compiled code background, you probably don’t even realize what you have been missing!  So, I have put this post together, it will hopefully make the developer experience better for at least a couple of you.  If you are currently debugging using a combination of alerts, console writes and breakpoints in the browser, listen up!


First off, you are going to need a project to debug.  I am going to use my most recent tutorial post on creating sprite sheets with Cocos2D if you want to download and follow along.  Of course, any project will work, but that particular project has an interesting… quirk that will come in useful.  Next, to get the most out of Webstorm debugging, you should also have Firefox installed.  If you are doing web development, I assume you do already anyways.  Alright, let’s get started.


Open the project up in WebStorm.

Now we want to create a debug profile.  In Webstorm, select Run->Edit Configurations…



In the resulting dialog, click the + icon:



Choose JavaScript Debug –> Local



On the left hand side, a new entry should appear.  Select it and file in the form like follows.  Navigate to your index.html or root HTML file, select Firefox from the browser dropdown and name it whatever you would like:


Click Apply then Ok when complete.


You are now ready to debug. 

Select Run-> Debug ‘Your App’ or press Shift + F9



Voila, or app should load up in our browser:



Now what we want to debug is debug the activity that occurs when the user presses a key.  Go back over to Webstorm, open MyFifthApp.js , locate the line with onKeyDown: function, and select the line right below it.  Here we want to set a breakpoint, which will cause our code to stop when the breakpoint is hit.  Set a breakpoint by hitting CTRL+F8 or selecting Run->Toggle Line Breakpoint.  You will see a red dot once your breakpoint is set, like so:



With the breakpoint set, now flip back to Firefox and hit a key.  This will immediately trigger the breakpoint, pausing your programs execution.  Now if you head back to Webstorm, there will be a wealth of information available to you:




There is quite a bit going on here.  Our code is currently paused executing on our breakpoint.  You can’t see it in the screenshot, but I am hovering my mouse over the e parameter, and it is popping up a tooltip showing its current value.  When debugging, you can interact with your code in a lot more detail.  Now lets take a closer look at the different bits of the interface here.


At the bottom left you have a very important window:



The toolbar on the left hand side can be used to resume program execution, stop completely, or to run from the beginning ( currently grayed out ).  When you are done with a breakpoint, you hit the resume button to continue your program execution.  The two buttons below on the toolbar are for managing breakpoints ( you can end up with a lot of them quickly! ), as well as to mute a breakpoint, which causes it not to fire DURING THIS DEBUGGING SESSION.  The next time you run your program, your breakpoint will be re-enabled unless you remove it.


To the right is something traditionally called a callstack, and it’s extremely useful.  Basically, it’s a hierarchy of the last functions called.  So in this case, you can see that our current ( anonymous) method inside MyFifthApp, was called by an anonymous method in CCKeyboardDispatcher, which was called by a different method in the same file.  Clicking the value in the callstack will immediately bring you to the line of code, where you can inspect the current value of any variables there.  Often the error actually occurs further up the callstack, so being able to trace backwards through a programs execution is incredible handy.


Next is an incredibly valuable toolbar, that controls your program’s execution while debugging.



These three are the most commonly used.

Step Over will cause your code to jump to the next line of code in the same file.

Step Into will jump into the code that you are currently on.  If it is a function for example, it will jump into the code for that function, even if it is in a different file.

Step Out backs you out, think of it like undoing a step into, you basically jump back into the calling code.

You use these 3 buttons ( or their hotkey/menu equivalents ) to run through your code as you debug.  There is also an option of run to cursor, which will run to whatever line of code your cursor is currently active on ( clicked on, not just hovering over ).


The program will update as it executes, so keep in mind, variable values will often be garbage, until the line they are allocated on is executed.


Next up is the Variables window.  Often called “Locals” in other IDEs:



This is a list of all locally declared variables.  Notice how indexAsString and prevPrefix are both shown, but valued as void?  This is because they haven’t been executed yet.  Lets take a closer look at that.  In WebStorm, locate the line this.removeChild(this.sprite), left click it to focus your cursor, then select run to cursor from the toolbar we just discussed:



As you can see from the blue line, or program execution continued to that point.  More importantly, if you look in the Variables window, they will now have values, since they have executed in the debugger:



You may also notice the + sign next to this.  That is because it isn’t a single value variable, so it is composed of other values.  Clicking the + icon will give you more details about the contents of that object:



Of course, often you want particular information about a specific variable.  This is where watches come in.  Say we want to see more details about this.sprite. In your code window, select all of this.sprite, right click and select Add To Watches.



Now details of that variable will be available in the watches window, at least, when it is in scope it will:



You can watch a number of variables at the same time.  Watches are especially useful for watching long lasting variables, like Director or when working in a browser, document.  Just like in the variables list, you can drill down to get more information on child values of the watched variable.


Another incredibly handy ability is the expression evaluator, invoked with this button:



The expression evaluator allows you to run any arbitrary code and see the value.  You can used it for example, to see what a function value would return.  Here for example, I am examining the results of calling this.sprite.getPosition().  Nicely, the expression evaluator has full code hints.






Finally, sometimes you want to debug code that is running from a server.  This is especially true if you are doing a number of AJAX or socket requests.  You can do this with Webstorm as well, with a few requirements.  First, you need to have a copy of the code installed locally, next you need to use Firefox for this part.


Let’s try it with our sample project, which exists on my servers at while you can download the project source code at


First we need to create a new remote debugging session.  In WebStorm, select Run->Edit Configurations…  Hit the + icon and selection JavaScript Debug->Remote.



Fill the resulting dialog out like so:



Click Apply then OK. Now everything else works exactly like it did before, with one exception.  Select Debug MyFifthApp Remote.

When you run your code and it hits a breakpoint, it will need you to tell it what file on the remote server matches the file the breakpoint is in.  Since we have a breakpoint set in MyFifthApp.js, when we run it, we will see:




Simply click the Set link, and a dialog will appear:


Simply type the URL of the remote file.  You only need to perform this once per file you set a breakpoint into.  You of course can perform this setup step in advance if you want.


Now you can locally debug code that is actually running on a remote server.


I hope you’ve found this guide handy.  In IDE debugging can make life a thousand times easier. 

General, Programming , , ,

15. August 2012


Today Sony released more information about the upcoming PlayStation Mobile launch.  If you have never heard of it, PlayStation Mobile is a development platform for creating games on the PlayStation Vita as well as a number of Android based devices.  Originally that list includedpsmlogo mostly just Sony’s line of Android devices but that is changing.  A few months back at E3 it was announced that select HTC devices, specifically the HTC One series of smartphones, would be supporting PlayStation Mobile.  Sony have just announced another two vendors have been added to that list. ASUS and WikiPad:


SCE also announced ASUS TeK Computer Inc. and WikiPad Inc. will join the PlayStation Certified license program.  By further expanding PlayStation Certified devices, SCE will deliver the unmatched PlayStation experience to even more smartphone and tablet users around the world. 

“Inspired by the diverse needs of consumers in all areas and phases of life, ASUS' foremost mission is to deliver truly innovative solutions that inspire consumers to reach for greater heights of productivity and fun. The ASUS Transformer Pad, which can transform from tablet to Notebook PC delivers this value,” said Samson Hu, Corporate Vice President & GM of Mobile Communications Products BU at ASUSTeK Computer Inc. “As a leading enterprise in the new digital era, ASUS offers PlayStation-like gaming experiences with the convenience of its array of products. With the Transformer Pad’s inclusion as a PlayStation Certified partner, we will surpass users' imaginations and change the rules of gaming.”

“Wikipad is the first true video game tablet built with an attachable gamepad controller that provides gamers with a mobile console experience. As we head into our upcoming launch, we are excited to be partnering with Sony Computer Entertainment.” said Fraser Townley, President of Sales Wikipad.Inc.  “PlayStation’s continued commitment to delivering innovative entertainment experiences that captivate gamers is unparalleled and we are thrilled to partner with them.”



I will admit, I had not heart of the WikiPad before today and I have to admit it is a cool looking device ( pictured right ) with a terrible name.  Of course, I have heard of Asus, in fact I own a Transformer personally and love the device.  With the quagmire that is the existing Google Play store, and alternative, especially a game focused alternative with Sony marketing and branding back it, could be an absolute godsend. Especially with a layer of quality control thrown over top, so we don’t get drown in a sea of “fart apps”.


One of the biggest handicaps Sony faces is market share.  If you are going to succeed, you need to attract developers.  In order to attract developers, you need to have an audience.  Every time they announce a new partner, that audience grows and so does the appeal to potential developers.


Speaking of which, Sony also announced a revised list of developers that are working on PlayStation Mobile titles, and it has grown a fair bit since E3.  Choice names on the list include ARC Systems Work, ASCII Media, FromSoftware, GameLoft, Nippon Ichi, SEGA, TECMO and THQ.



Buried in the announcement was this blurb as well:

In conjunction with the launch of dedicated content for PlayStation Mobile through PlayStation Store, legendary PlayStation games (PS one® Classics)  for PlayStation Certified devices will no longer be offered


I am not completely sure how to interpret that statement.  I believe it means they be moving the PS One classics into the store, but I am not positive. 


The launch has been announced as “this fall” and will be available initially in the following countries:  Japan, United States, Canada, United Kingdom, France, Germany, Italy, Spain, and Australia.



If you are interested in getting started with PlayStation Mobile SDK, the Beta SDK is available for free right here.  It is a C# based SDK running on top of OpenGL.  Of course, this site has a series of PlayStation Mobile SDK tutorials to get you started.

News ,

14. August 2012


This tutorial covers the process of creating and using a spritesheet.  A spritesheet is a collection of individual sprites grouped together into a single image.  I created the spritesheet for this tutorial using TexturePacker.  I already documented the process in this tutorial, the only difference is you set the Data Format to Cocos2D instead of Generic XML.  The spritesheet and all of the sprites that went in to making it are included in the archive at the end of this tutorial.


The cocos2d.js and main.js files are relatively unchanged:



(function () {
    var d = document;
    var c = {
    window.addEventListener('DOMContentLoaded', function () {
        var s = d.createElement('script');
        s.src = c.engineDir + 'platform/jsloader.js';
        s.c = c; = 'cocos2d-html5';

The only real different here is the file name passed in the appFiles array.



var cocos2dApp = cc.Application.extend({
    ctor:function (scene) {
        this.startScene = scene;
        cc.COCOS2D_DEBUG = this.config['COCOS2D_DEBUG'];
        cc.Loader.shareLoader().onloading = function () {
        cc.Loader.shareLoader().onload = function () {

    applicationDidFinishLaunching:function () {
        var director = cc.Director.getInstance();
        director.setAnimationInterval(1.0 / this.config['frameRate']);
        director.runWithScene(new this.startScene());

        return true;
var myApp = new cocos2dApp(MyFifthAppScene);


There are only two changes here.  First we added spritesheet.plist to the preloader list.  plist files are short for Property List is a configuration format used in Mac/iOS development, but at the end of the day, it’s just data in an XML format.  This file was generated for us by TexturePacker and it describes the details and locations of each sprite within the spritesheet, indexed by the original file name.  The other difference is we pass MyFifthAppScene to our new cocos2dApp call.


Let’s take a look at ( a portion of ) the file spritesheet.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "">
<plist version="1.0">


The details of the file aren’t important, Cocos2D does all of the heavy lifting for us.  Just be aware that it describes the general layout and name of each sprite within your spritesheet. Now let’s take a look at MyFifthApp.js where the majority of our changes occurred:


var MyFifthApp = cc.LayerColor.extend({
        this.initWithColor(new cc.Color4B(0,0,0,255));
        var size = cc.Director.getInstance().getWinSize();

        var cache = cc.SpriteFrameCache.getInstance();
        cache.addSpriteFrames("spritesheet.plist", "srcSprites/spritesheet.png");

        this.sprite = cc.Sprite.createWithSpriteFrameName(this.spriteFrameNamePrefix + "00.png");
        this.sprite.setPosition(new cc.Point(300,300));

        return this;
        if(e == cc.KEY.left || e == cc.KEY.right){
            var prevPrefix = this.spriteFrameNamePrefix;
            if(e == cc.KEY.left)
                this.spriteFrameNamePrefix = "Walk_left";
                this.spriteFrameNamePrefix = "Walk_right";
            if(prevPrefix !== this.spriteFrameNamePrefix)
                this.spriteFrameIndex = 0;

            if(this.spriteFrameIndex > 18)
                this.spriteFrameIndex = 0;
            var indexAsString;
            if(this.spriteFrameIndex < 10)
                indexAsString = "0" + this.spriteFrameIndex.toString();
                indexAsString = this.spriteFrameIndex.toString();

            this.sprite  = cc.Sprite.createWithSpriteFrameName(
                this.spriteFrameNamePrefix + indexAsString + ".png"

            this.sprite.setPosition(new cc.Point(300,300));

MyFifthAppScene = cc.Scene.extend({
        var layer = new MyFifthApp();


I wont bother going in to detail on MyFifthAppScene, we’ve done that enough times already.  In MyFifthApp we declare a sprite variable to point at the currently active sprite, then declare spriteFrameNamePrefix and spriteFrameIndex.  We access the sprites within the sprite sheet using the keys defined in the plist ( the file name ), of which there are 18 frames for walking left and right:

Walk_left00.png –> Walk_left18.png

Walk_right00.png –> Walk_right18.png


We will be building this key dynamically as we switch between sprites.


I am only going to cover the new stuff here, the rest should be pretty familiar at this point.  Cocos2D has a built in cache for Sprite frames ( in cocos2D a SpriteFrame is an individual sprite within the spritesheet, while a spritesheet is a SpriteFrames (<- note, plural ) ), the singleton SpriteFrameCache.  We add a new spritesheet to it with the call addSpriteFrames, passing in the name of the plist we preloaded earlier in main.js, as well as the path to the spritesheet graphic.



Speaking of which, this is spritesheet.png that TexturePacker generated:


We then get our sprite reference from the spritesheet with a call to createWithSpriteFrameName, passing in the key of the sprite specified in the plist.  In this case we are starting with Walk_left00.png.  We then position the sprite at 300,300, scale it to 3x it’s size and add it to our layer.  Finally we tell Cocos we want to handle keyboard events with a call to setKeyboardEnabled().


Next in the onKeyDown handler we check to see if the user has pressed ( and released ) the left or right arrow.  Depending on which direction we are walking, that determines which prefix to use for accessing the sprite sheet, left or right.  Next we check if the direction has changed since the last frame, if so, we start the frame index back to 0 to start the animation over.


Next we check to see if we’ve exceed our 18 frames, if we have we roll over to 0.  Next we check to see if our index is a single digit ( 0..9 ), in which case we pad it with a 0, so 1 becomes 01.  This is simply because that is how the source frames were named when I imported them to TexturePacker.  We remove our current ( about to be replaced ) animation frame from the layer. We then put our prefix, index and “.png” together to get the key to the next frame of animation, we access with using createWithSpriteFrameName again.  We position and scale the new sprite frame and add it to the scene to replace the previous frame.  Finally we advance to the next frame index.



Here is our game in action.  Be sure to click in the window to focus keyboard events, then use Left and Right arrows to walk:

This code wouldn’t run when I first deployed it live to my IIS server but worked fine in Apache!  The XML loader in CCSAXParser.js was failing, and it turned out to be a permissions issue.  When you deploy a new file extensions ( like plist ) to IIS, you need to be sure to add it as an allowed mime type!


For the record, there are actually better ways to handle animation that we will cover in a later tutorial. This tutorial does however illustrate how to load a sprite sheet and access individual sprites. You can download the entire archive here.

Programming , ,

Month List

Popular Comments