Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

24. August 2012

 

As of right now we have exactly nothing, so anything is an improvement.  Let’s start our game journey off with a bang… or at least a window.  Without further ado, some code:

 

screenWidth = MOAIEnvironment.screenWidth
screenHeight = MOAIEnvironment.screenHeight
print("Starting up on:" .. MOAIEnvironment.osBrand  .. " version:" .. MOAIEnvironment.osVersion)

if screenWidth == nil then screenWidth =640 end
if screenHeight == nil then screenHeight = 480 end

MOAISim.openWindow("Window",screenWidth,screenHeight)

viewport = MOAIViewport.new()
viewport:setSize(screenWidth,screenHeight)
viewport:setScale(screenWidth,screenHeight)

layer = MOAILayer2D.new()
layer:setViewport(viewport)

MOAIGfxDevice.setClearColor(1,0.41,0.70,1)
MOAIRenderMgr:pushRenderPass(layer)

 

Save that code to a file named main.lua and you have just successfully created your first Moai application!  Well, unless of course you have already created Moai applications before coming here… in which case we have just created our first Moai application!  Huzzah!

 

Now run it.  If you followed my earlier tutorial about setting up IntelliJ to work with Moai, it is simply a matter of selecting Tools->Moai->Run Moai.  If you added gluthost.exe to your path, you can also run by opening a command prompt, navigating to the folder you saved main.lua to and  typing moai main.lua.  If you’ve done neither of these things, well, you are on your own about figuring out how to run it.

 

Anyways, here it is running in all of its glory!

image

 

It’s a window, its 640 pixels wide, 480 pixels high and its pink.  Hot pink to be specific.

 

We all start somewhere.

 

Whatcha talkin ‘bout Willis?

 

So, what exactly have we done here?

 

Well, lets take it from the top.

screenWidth = MOAIEnvironment.screenWidth
screenHeight = MOAIEnvironment.screenHeight

 

Here we are simply getting the screen width and height from the global MOAIEnvironment object.  MOAIEnvironment stores a ton of information about the platform it is being run on when the application starts up.  Considering that Moai code can run on PC, Mac, iOS and Android, details about your environment are obviously quite useful.

 

MOAIEnvironment currently holds the following values:

  • appDisplayName
  • appID
  • appVersion
  • cacheDirectory
  • carrierISOCountryCode
  • carrierMobileCountryCode
  • carrierMobileNetworkCode
  • carrierName
  • connectionType
  • countryCode
  • cpuabi
  • devBrand
  • devName
  • devManufacturer
  • devModel
  • devPlatform
  • devProduct
  • documentDirectory
  • iosRetinaDisplay
  • languageCode
  • numProcessors
  • osBrand
  • osVersion
  • resourceDirectory
  • screenDpi
  • screenHeight
  • screenWidth
  • udid

 

Additionally MOAIEnvironment has methods for generating a GUID ( a big unique identifier ), getting the network MAC address ( not exactly sure why this got it’s own function ) as well as for setting new values.  That said, the above list is pretty self explanatory, so lets move on.

 

print("Starting up on:" .. MOAIEnvironment.osBrand  .. " version:" .. MOAIEnvironment.osVersion)

Dump the OS name ( “Mac/Windows/Android/etc” ) and Version ( “10.5/XP/etc”).  Interesting note, I am running on Windows 8 Consumer preview and version doesn’t exactly work well.  So, why did I do this?  Just because…  I suppose it might be of interest to see how easy it is to put debug information to the console.

 

if screenWidth == nil then screenWidth =640 end
if screenHeight == nil then screenHeight = 480 end

Here we are checking to see if our screenWidth and screenHeight values returned from MOAIEnvironment are nil or not.  If they are in fact nil, we set them to a default of 640x480 or whatever other resolution you happen to like.  This check is actually extremely important in this case as MOAIEnvironment actually returns nil for both of these values when running using the default glut host!  It is up to the host to provide the information, so don’t count on it being there!

 

MOAISim.openWindow("Window",screenWidth,screenHeight)

Finally we create our window, at the full screen resolution if available or 640x480 otherwise with a title of “Window”.  Inventive eh?  I thought so, that took hours to come up with.

 

You may be asking yourself “What the hell is a MOAISim”?  That there, is a good question!  MOAISim is short form for MOAISimulation, it is a global object that we can consider the keeper of all things time related.  In a sense it is the heart of your application, but you don’t interact with it all that often.  Oh, and it is responsible for opening windows for reasons I’m not exactly sure of ( as well as going full screen ).  You should check it out when you have some spare cycles, it contains a hodgepodge of important stuff.  For now though, just realize it’s what opens your window, and without a window, we’ve got nothing.  Simply put, you have to call MOAISim.openWindow() at some point, period.

 

Now that we have a window, we now create a viewport into our world.  If you are thinking the analogies are getting a bit confused now that our window has a window in it, I suppose that is true.  Although, if you remember the Subaru SVX, it’s window had a window in it…

 

subaruSVX

 

God I loved that car… oh, wait sorry, going off topic here.  Don’t blame Moai for the mixed metaphor, the whole window/viewport thing way predates them, so get used to metaphors with windows within windows. Back to the next bit of code:

 

viewport = MOAIViewport.new()
viewport:setSize(screenWidth,screenHeight)
viewport:setScale(screenWidth,screenHeight)

 

Anyways, think of a window as the actual thing you are going to render to, such as the screen of your phone, or the window your application is running in( if on a Mac or PC ).  A viewport on the other hand, is a view into your game world.  Your world itself can be many times larger than a single window and a viewport controls which portion of it to view at any given time.

 

Generally, unless you have multiple viewports ( think picture in picture ), you will always size the viewport to the same dimensions as the screen in the setSize() call.  setScale() will often be set to the same size as well, if you want pixels in the world to be 1 to 1 with pixels on the screen.  setScale is used to scale world pixels to screen pixels.  If you’ve got no idea why you would want to do this, or you want your pixels to be the same size on screen as in the world, simply passed the same values into setScale as you did into setSize.  If you really want a mindtrip, try to decipher the official documentations explanation!

Sets the number of world units visible of the viewport for one or both dimensions. Set 0 for one of the dimensions to use a derived value based on the other dimension and the aspect ratio. Negative values are also OK. It is typical to set the scale to the number of pixels visible in the this-> This practice is neither endorsed nor condemned. Note that the while the contents of the viewport will appear to stretch or shrink to match the dimensions of the viewport given by setSize, the number of world units visible will remain constant.

 

I neither endorse, nor condemn trying to make sense of that! Winking smile  Nicely, for 99% of people, you will just use the same value for both and be done with it. Ok, moving on:

 

layer = MOAILayer2D.new()
layer:setViewport(viewport)

So, we’ve got Windows and viewports and now we have layers.  If you’ve ever used Photoshop or The GIMP, the concept of a layer should be instantly understandable to you.  Way back in the stone age of animation, people making animated movies used to draw on cel(uloid), which were transparent overlays ( or layers! ) over a static background.  By merging all of these cels and a static background together, you end up with your finished animation.  Consider this diagram I brazenly ripped off from this site:

 

celanimation

 

That diagram pretty much represents how layers work.  Your application will have one or more layers ( at least one ), and layers will be composed of stuff ( scientifically correct term ) to be displayed.  In our case, that stuff is the color pink…   So, anyways… we create a new MOAILayer2D called layer, then apply our viewport to it, telling Moai which portion of our layer to look at. 

 

MOAIGfxDevice.setClearColor(1,0.41,0.70,1)
MOAIRenderMgr:pushRenderPass(layer)

And here is where we bring the pink.. er, hot pink.  MOAIGfxDevice is another global object referred to as a Singleton.  In some circles, that is a swear word, but fortunately not here.  Basically a Singleton means it is a global object, so you can use it anywhere, and that, like Highlanders, there can be only one.  This of course is where the Single of Singleton comes in.  Anyways, MOAIGFXDevice is a singleton representing the graphic’s device ( think GPU ), although to be honest, beyond setting the background color and a few other things, you wont really use it all that much.  At least, I don’t think you will.

 

So, what exactly are the values I passed in to setClearColor anyways?  Well those are red, green, blue and alpha values, with values ranging from 0 to 1.  Alpha is the level of transparency, with 0 being transparent, while 1 is opaque.  If you are wondering how I came up with the values for hot pink, simple… I found an HTML color chart which had all the colors represented as values from 0-255, and simply divided each color value by 255 to get it’s decimal value.

 

Now on to MOAIRenderMgr, hey, guess what, it’s a singleton too!  I guess we know where the ton part of singleton comes from, eh?

 

Anyways, MOAIRenderMgr is all about controlling what is going to be drawn each frame, and that is managed by pushing a ton of MOAIRenderable objects on it using pushRenderPass.  Of course, layer just so happens to inherit from MOAIRenderable.  Now, if you currently look at any of the official samples, they actually call MOAISim.pushRenderPass(), but this has been deprecated, meaning if you use it, sometime in the future Moai developers will come into your house and defecate on your rug.  Or something like that.  Anyways, use MOAIRenderMgr going forward and bad things wont happen to you or your rug.

 

 

 

And that, there, is the end of the first tutorial.  As these things we just covered are the absolute fundamentals of every single application, I went into more details than I generally will in the future.  This means two things, if you read future tutorials, I expect you to have read and understand the prior tutorials, so I wont be covering things I have already covered.  Second, they will be much shorter, meaning less eye strain from you and less finger strain from me.

 

Programming , ,

22. August 2012

 

The following is a guide on how to download and configure IntelliJ IDEA for use with MOAI/LUA development.  It is based heavily on information found in this thread, although it goes into a great deal more detail and uses the most recent versions as of 8/22/2012.

 

First and foremost, go and download IntelliJ IDEA from this link.  Assuming you don’t want to spend money, use the Community Edition version.  I have the full version of WebStorm and sadly, it isn’t fully compatible with the following steps.  Once your download completes, run the installer.

 

Once installed, run IntelliJ.  Select the menu File->Settings:

image

 

On the left hand side, scroll down and locate Plugins, and highlight it:

image

 

On the right hand side, locate and click Browse repositories…

image

 

In the resulting dialog, in the top right search box enter Lua.  Then locate Lua in the results and double click:

image

 

A confirmation dialog should pop up, choose ‘Yes’

image

 

In the status bar at the bottom of the window, a download progress bar will appear, wait for it to complete.  Now click OK on the Browse repositories dialog to close it, then Apply in the Settings window.  You will be prompted:

image

 

Choose Restart.  Let IntelliJ restart.

 

Now head over to this thread and download the attached file moai_sdk.zip. ( Or use this direct link ).  Save that archive and extract it’s contents somewhere (permanent ).  In my case I used C:\APIs\moai-sdk\IntelliJ which is a sub-directory I created under my MOAI install folder, the actual location doesn’t really matter.

 

Now in IntelliJ IDEA, create a new Lua project.  Select File->New Project… Check ‘Create project from scratch’, then click Next:

image

 

 

In the bottom left under ‘Select Type’ select Lua Module, then fill in a project name and location.  Click Next:

image

 

Kahlua should display as Lau SDK version, click the Finish and your project will be created.

 

Now on the left hand side in the Project panel, expand External Libraries and right click Kahlua and select ‘Open Library Settings’ ( or hit F4 )

image

 

In the resulting Window, under the Classpath tab, click the small ‘+’ icon.

 

image

 

Now navigate to the directory you extracted the archive to earlier and select the directory then click OK.  It should update like this:

image

 

Click Apply, then OK to close the Settings window.

 

You are now setup to do LUA/MOAI development in IntelliJ, but… IT DOESN’T WORK UNTIL YOU RESTART. Alright, done yelling, just figured that point was important.  For some reason, intellisense wont start working until you restart IntelliJ, so do that now.

 

Now create a new LUA script.  Right click your project in the Project panel, select New->Lua Script:

 

image

 

Call it main.lua and click OK:

 

image

 

Now if you start typing, autocomplete will work:

 

image

 

And Presto!  Don’t worry, all of that work takes perhaps two or three minutes, it just looks like a ton of work because of the level of detail I went into.  Now onto…

 

 

Configuring IntelliJ IDEA to run you Moai game

 

Ok, so this part is completely optional, but will make it easier for you to run a game directly from IntelliJ.  We are going to create a pair of External Tools.  Again, it will look harder than it is.

 

In IntelliJ, select File->Settings:

image

 

On the left hand side, scroll down and locate External Tools and select it:

image

 

On the right hand side, locate the + icon and click it:

image

 

In the Edit Tool dialog, name it Run Moai, in the group Moai, set the Program: value to point to where you’re MOAI host is, in my case c:\Apis\moai-sdk\bin\win32\moai.exe for parameters set it to $FileName$, which is a macro for the current selected files name; then set Working Directory to $FileDir$, which will expand to the current files directory.  Now click OK.

 

image

 

Click Apply and OK on the External Tools window to close it.

 

Now you need some code to run.  If you don’t have any code to enter in Main.lau, use the following bare bones application for testing purposes.

MOAISim.openWindow ( "test", 320, 480 )

viewport = MOAIViewport.new ()
viewport:setSize ( 320, 480 )
viewport:setScale ( 320, -480 )
viewport:setOffset ( -1, 1 )

layer = MOAILayer2D.new ()
layer:setViewport ( viewport )
MOAISim.pushRenderPass ( layer )

 

Once you’ve added that code to main.lau, save it, then in the menu select Tools->Moai->Run Moai like so:

 

image

 

If the menu isn’t there, something went wrong with the prior setup, make sure that you clicked Apply after editing.  After you select Run Moai, your application should appear:

 

image

 

Tada!

After it runs, you will see the results of the console window in IntelliJ’s Run panel, like so:

 

image

 

If it doesn’t, and you have an error like the following:

image

 

Make sure that you have your .lua file selected before you choose Run Moai.  Simply click it in the editing window before running.

 

 

 

This setup does however present a bit of a problem… MOAI logs errors out to the standard console while it is running, but IntelliJ will only display the console once running is complete.  This obviously isn’t ideal if you are trying to debug your application or if non-terminal errors are occurring, but don’t worry, there is an easy fix.

 

 

Configuring IntelliJ to run Moai in a separate console/terminal window

 

See, sometimes we want to launch a terminal window that launches our Moai host.  This process is remarkably similar with a minor tweak.

 

Once again, select File->Settings. Scroll down and select External Tools, on the right hand side select Moai then click the + icon. In the Edit Tool dialog, fill it out as follows:

 

Name it ‘Run Moai with Command Prompt’, select the Group Moai.

Under program enter cmd.exe

Under Parameters, enter ( obviously adjusting to your Moai install directory ): /c START C:\APIs\moai-sdk\bin\win32\moai.exe $FileDir$\$FileName$

Under working directory, enter: $FileDir$

 

image

 

 

Then click OK to close the Edit tool window, then Apply then OK to close the Settings window.

 

Now click inside moai.lua to focus it, then choose the menu Tools->Moai->Run Moai with Command Prompt:

 

image

 

 

And Voila:

image

 

Moai running, with a command prompt receiving output.  I added a print statement to the sample code to generate a bit of output.

 

 

There you go, a fully configured IDE for creating and running Moai applications in IntelliJ IDEA with auto complete.  The only downside is, the text completion is not smart enough to figure out dynamic values.  For example, it cannot handle : completions like this:

viewport = MOAIViewport.new ()
viewport:setSize ( 320, 480 )

 

It will offer auto completion on the first line, but has no idea the members in the second, so if you type viewport: you will get no recommendations.  If you know a way to fix this, please let me know!

 

Hope that guide proved useful.

Programming, General , ,

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 https://dashboard.moaicloud.com/download.php 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…

 

image

 

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:

image

 

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 = MOAIViewport.new()
viewport:setSize( 800,600)
viewport:setScale( 800,600)

layer = MOAILayer2D.new()
layer:setViewport(viewport)

MOAISim.pushRenderPass(layer)

chars = 'DEHLORW'

font = MOAIFont.new()
font:loadFromTTF('courier.ttf',chars,120,72)


text = MOAITextBox.new()
text:setString('Hello world')
text:setFont(font)
text:setTextSize(120,72)
text:setYFlip(true)
text:setRect(-400,-300,400,300)
text:setAlignment(MOAITextBox.CENTER_JUSTIFY,MOAITextBox.CENTER_JUSTIFY)

layer:insertProp(text)

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:

image

 

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…

image

 

In the resulting dialog, click the + icon:

image

 

Choose JavaScript Debug –> Local

image

 

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:

image

Click Apply then Ok when complete.

 

You are now ready to debug. 

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

image

 

Voila, or app should load up in our browser:

image

 

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:

image

 

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:

 

image

 

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:

image

 

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.

 

image

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:

image

 

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:

image

 

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:

image

 

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:

image

 

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.

image

 

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

image

 

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:

image

 

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.

 

image

 

 

 

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 http://www.gamefromscratch.com/downloads/cocos2d/run/MyFifthApp/index.html while you can download the project source code at http://www.gamefromscratch.com/downloads/Cocos2d/zips/MyFifthApp.zip.

 

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

image

 

Fill the resulting dialog out like so:

image

 

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:

 

image

 

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

image

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

Month List

Popular Comments