Friday 8 May 2015

Smooth Animations In Your Browser With requestAnimationFrame()

In the last post, we discussed how to bring your game to life by animating your controllable character with sprites.

The key to achieving a smooth animation using this method, is to make sure that we achieve an acceptable frame rate.

In this post, we will talk about frame rendering in the browser, and particular the requestAnimationFrame() API that we have available to us.

The rate at which frames are painted to the screen can make our animations seem very silky smooth as the rate gets higher (to a certain point).

Our computer monitors refresh rate is usually set to 60 herz, so any frame rate above that would be overkill.

To try to achieve a 60fps rate, we must paint a new frame every 16.666 milliseconds (1000ms/60fps).

Before the days of requestAnimationFrame(), we had available to us, two methods of animating in javascript:

setInterval() and setTimeout().

Both functions take a function and a timer as an argument.
The difference between them is that setInterval will call the passed function at the rate your timer specifies.
The setTimeout function, will only call the function once, after the timer passes.

The following block of code shows you how you could use the setTimeout function to draw some animations on a canvas for instance:

1
2
3
4
5
function draw() {
    setTimeout(draw, 16);
    // Drawing code goes here
}
draw(); 

This will, in essence, call the draw function every 16 milliseconds.
This is perfect, everything we need, right?

Wrong...

There is a problem with using this method, as we never take into account what else is going on in the browser while the timer is ticking down.
Firstly, the animation could be behind a hidden browser tab.
In chrome, the function is throttled to 1fps, but you cannot depend on this in other browsers.
The animation could be using some needless resources.
Also, if the animation is scrolled off the page, there is no need to repaint it every time.

It all seems like a bit of a waste...

Furthermore, the browser has to juggle the painting of your animation along with its own re-rendering of the browser window, whenever anything else happens, like scrolling or clicking for example.

It would be nice if we could paint everything in sync, and use up a lot less resources.

requestAnimationFrame() to the rescue!

We can use this API to ask our browser to call a certain function when it is ready to repaint the screen, which is usually at 60fps.

The browser will then decide best when to call the function, and it will take into account all the issues we just described above, giving you a smooth 60fps animation without using up as many resources as we used when calling setInterval().

The following block of code illustrates how we could utilize this API to smoothly animate your canvas:

1
2
3
4
5
function draw() {
    requestAnimationFrame(draw);
    // Drawing code goes here
}
draw();

It is very similar to the code we had before, except now we use the new function and we do not specify a frame rate.

If you want to control the frame rate yourself, you could simply wrap the call to requestAnimationFrame() in a setTimeout() block like so:

1
2
3
4
5
6
7
var fps = 15;
function draw() {
    setTimeout(function() {
        requestAnimationFrame(draw);
        // Drawing code goes here
    }, 1000 / fps);
}

Browser compatibility has not been perfect, so you can find a shim here to allow you to hide the nasty details of accessing the API across browsers:

CanvasQuery uses requestAnimationFrame() under the hood in your game loop, so you do not have to worry about it.

However, it is useful to know what is going on if you really want to get a handle on your animations!

Until next time...

Friday 24 April 2015

Animating Your Game Characters With Sprites

Welcome back to building a 2D mobile game with Cordova and Canvasquery/Playground.

In the last episode, we got a simple scene up and running, where you could control a red box on a html5 canvas by using the keyboard arrows.

See the demo here

This is a really simple example of what can be done with the Playground and Canvasquery libraries.

Let's take this a step further by replacing our red square with a picture of a bird, or better yet a series of pictures that will lead to the illusion of a moving bird.

You can see this in action here

Animations are made up of frames, and each frame is swapped out at ever step for the next one in the queue.
If you play the frames fast enough, it gives the illusion of a moving character.

How we will achieve this is by using what is called a sprite.

A sprite is a 2D strip of images of an object at different stages of movement.
All of the images are glued together to form one image.

It looks something like this:


You can create your own sprites or download one from various free libraries on the web.

If you crop the right parts of the image when you display it at each stage, you can select a certain frame from the sprite.
The most common way to make an animation from this is to crop the image from left to right, moving over one image length at a time.

Ok, so now to the implementation details.

We can load images into our canvasquery app by using:

playground.loadImages("bird_right")

where playground is the instance of your playground app you created with the playground() constructor.

The text you pass to loadImages will be the name of the image in the public/images directory, without the file extension, that you are trying to load.

The best place to call this method this is in the "enter" callback of your game state, so that the image will be ready for the render step.

add this code to your game_screen.coffee file from the last tutorial:

enter: ->
      game.loadImages "bird_left"
      game.loadImages "bird_right"

      @player = new Player(new Point(100, 100))

This code loads the images into our app into a hash called images. The keys in this hash are the names that you passed into loadImages.

So for example, you can access the bird_right image with game.images.bird_right, where game is the playground instance we create.

You can download the sprite from above and place it in the src/images directory in the project.

I have added a grunt task (grunt copy:assets) to the project that will copy all assets from the source images directory into the public/images directory where they will then be served from. Have a look in the tagged source

Now that we have our sprite loaded, we want to paint it at the current position of our square.

What I would recommend doing for this is abstracting away the position of the square into a Player class, as we will use this class to store more attributes relating to the character at a later stage.
We will also make a Point class which will be used to store the x, y coordinate of the player.

With these classes created (you can reference the tagged source for this), we can now retrieve the position of the player and draw a portion of the image sprite instead of the red square.

To do this, we have to rotate over the frames in the sprite. So, we create a method in the Player class getNextSprite()

Player::getNextSprite = ->
   delta = (Date.now() - @lastTick) / 1000
   frame = 8 * (delta % @duration / @duration) | 0
   
   offset = 19

   sprite = [
     offset + (frame * 109)
     28
     109
     100
   ]
   
   #console.log(frame + " " + sprite);
   sprite

This function returns a set of cropping dimensions for our sprite.
It is specific to that sprite. It can be tedious to get this perfect,
but you can use a tool like gimp to help you out.

The formulas in there basically calculate what frame should be returned at any time, in such a fashion that it makes corrections for CPU lag etc.

We now take those dimensions and crop the sprite using them in the render step, with the following code:

render: (delta) ->
      game.layer.clear("#7EC0EE")
      #.fillStyle("red")
      #.fillRect(@player.position.x, @player.position.y, 50, 50)

      game.layer.drawRegion @player.getImage(), @player.getNextSprite(), @player.position.x, @player.position.y

The drawRegion method of Canvasquery takes as arguments the image to be drawn, the dimensions to crop the image, then the x and y coordinates to draw the cropped image. See Here

The x and y coordinates we simply read from the Player class.

The image, we load from our images hash we talked about earlier.
But we see that we are calling out to the player class here to ask for the correct image.

The reason we do this is that I have actually loaded two game sprites.
One for when the player is facing right and one for when he is facing left.

Depending on the direction, we return the appropriate image, to make it look like the player is actually flying in the right direction.

Again, take a look at the demo to see this in action!

I think we will leave it there for this post.

It is plain to see that this simple technique makes a big difference in bringing your game to life.
Already, we can see that we are getting the basic shape of the game together.
In the next post, I will talk about smooth animations with the requestAnimationFrame() browser API.

Until Then...

Thursday 26 March 2015

Introduction To Playground and CanvasQuery

Welcome back to building a 2D mobile game with Cordova and Canvasquery.

We will continue on from our last post, by creating a simple 2D game that shows a box on the screen. The box will travel to any point you click on the canvas. Groundbreaking stuff! The fancy stuff will come later once we get the basics in.

You can see a running version of the app we are trying to build in this post here

Here is a simple screenshot of what we are trying to achieve at this very basic level:


I have included the source code of the project we are working on in tandem with this blog, and will link to the tags where necessary.

Here is the tagged version of the codebase, relating to this blog post.
And here is the current codebase.

Now that we have our project set up, it is time to add some libraries to do some heavy lifting for us.
We will add the canvasquery library.

Canvasquery is a wrapper for a raw html5 canvas.
It works together with playground to provide some really nice utility methods for creating animations etc.
Playground translates key codes into human readable strings to help us keep our code clean and readable.
Canvasquery provides the ability to chain methods together, when drawing on a canvas.
In addition, canvasquery provides us with the very handy stars() method. See Here

I placed the Javascript files for the library into cgsrc/src/javascripts/lib.
Again, these will be compiled into our main Javascript file when we run the Grunt requireJS task.

We then define a template for our game using what are known in playground as game states.
A state will represent different screens in your game, such as "main menu" or "game screen".
This allows you to keep your project modular and reduces complexity.

Let's continue to create a simple game that allows you to control an on screen object with the keys.

For this we will create two games states: main_menu and game_screen.
However, we must first initialize playground.

Create a file called game.coffee in the src/coffeescripts directory with the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
define ["require", "playground"], (require, playground) ->

  game = playground
    mouseToTouch: true

    width: 1600
    height: 900
    scaleToFit: true

    create: ->


    ready: ->
      @setState require("main_menu")

  return game

This will define the skeleton for our game and set it to fix into a 16:9 ratio.
the ready callback basically sets the initial state of the game.
We will create the main_menu_state next.

Create a file main_menu.coffee in the src/coffeescripts directory with the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
define ["require", "game"], (require, game) ->
  main_menu =
    create: ->

    ready: ->

    step: (delta) ->

    render: (delta) ->
      game.layer.clear "#FFF"
      game.layer.fillStyle("#000").font("64px Arial")
        .fillText "Click The Mouse To Play!!!", 100 / game.scale, 100 / game.scale

    mousedown: (event) ->

    mouseup: (event) ->

    mousemove: (event) ->

    keydown: (event) ->

    keyup: (event) ->

    touchstart: (event) ->

    touchend: (event) ->
      game.setState require("game_screen")

    touchmove: (event) ->

  return main_menu

This is a skeleton that you can use to create any game state.

Basically, a game state is just a JSON object that has some callbacks and properties in it.
It has callbacks for different events that you can hook on to relating to keyboard and mouse input.

You respond however you like to any of the events, but for now, all this does is displays some text and responds to the click event by setting the games state to the main game screen which we will create later.

Note here that we have a property mouseToTouch: true defined in our game.coffee file.
This will tell playground to translate all of our mouse events to touch events so that we only have to worry about touch events and our app will work across both mobile and desktop.
This is why you see that we are using the touchEnd callback in the main_menu to transition to the game screen.
When you click the mouse it will be translated into a touch event.
Handy!

The 'ready' function gets called when this state is loaded.

The two functions step and render are really important for the main game screen.
Basically, the idea is that we have a game loop which is handled by playground.
This loop runs constantly, and is responsible for calling a sequence of callbacks in our state JSON in order for you to provide your game logic.
The step callback is basically where you put your game logic, update your game world/process user input/make any calculations for the users score etc.

Then the render callback is where you draw your game state. Under the covers, playground uses the requestAnimationFrame API provided by our browser, to ensure we have sharp animations. More on this in a future post.

See here for more information on the game loop.

Now we need to hook our menu state up to our game object that we defined above in our first file game.coffee.
To do this, we go back to our app.coffee from the previous tutorial.

In this file we simply printed out some text when the app loaded.
Now, instead, we would like to load in "game" and set some states on it.
Replace the content of app.coffee with:

1
2
3
4
define ["require", "jquery", "canvasquery", "playground", "game", "main_menu", "game_screen"],
(require, $, cq, playground, game, main_menu, game_screen) ->
 game.main_menu = main_menu
 game.game_screen = game_screen

We will also hook up our game_screen state here that we will create later.
To transition to any state, you simply call game.setState(stateObject), where stateObject is the JSON representing the state you wish to transition to.

Notice we also pull in dependencies for our libraries at the top here.
For our libraries to play nicely with requireJS, we must declare to requireJS that these libraries export globals.

Do this by adding a shim section to the config.coffee file:

1
2
3
4
5
6
7
8
shim:
    playground:
      deps: ["canvasquery"]
      exports: "playground"
    canvasquery:
      exports: "cq"
    brain:
      exports: "brain"

At this point, lets compile our project with grunt dist.
Now if we run our rails server and go to /game you should see a screen that asks you to click the mouse to start!
Finally we can start seeing some progress on screen for our efforts!

However, clicking the mouse causes an error relating to our missing game state, let's resolve that!

Just like before, create a skeleton game state in a file src/coffeescripts/game_screen.coffee with the content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
define ["game"]
, (game) ->

  game_screen =
    gameWidth: 1600
    gameHeight: 900

    x: 10
    y: 10

    lastTouchX: 0
    lastTouchY: 0

    followLastTouch: false

    enter: ->

    ready: ->

    step: (delta) ->
      @checkKeyPresses()
      @checkTouches()

      #make sure we don't go outside the screen bounds
      if @x < 0
        @x = 0

      if @x > @gameWidth - 60
        @x = @gameWidth - 60

      if @y < 0
        @y = 0

      if @y > @gameHeight - 60
        @y = @gameHeight - 60

    render: (delta) ->
      game.layer.clear("#7EC0EE")
      .fillStyle("red")
      .fillRect(@x, @y, 50, 50)

      #game.layer.drawRegion player.getImage(), player.getNextSprite(), x, y

    mousedown: (event) ->

    mouseup: (event) ->

    mousemove: (event) ->

    keydown: (event) ->
      @followLastTouch = false

    keyup: (event) ->

    touchstart: (event) ->
      @followLastTouch = true
      @lastTouchX = event.x
      @lastTouchY = event.y

    touchend: (event) ->

    touchmove: (event) ->

    checkKeyPresses: ->
      if game.keyboard.keys["right"]
        @x+=20
      else if game.keyboard.keys["left"]
        @x-=20

      if game.keyboard.keys["up"]
        @y-=20
      else if game.keyboard.keys["down"]
        @y+=20

    checkTouches: ->
      if @followLastTouch
        console.log(@lastTouchX + " " + @lastTouchY)
        #move the object towards the current touch

        if @lastTouchX >= @x
          @x+=20

        if @lastTouchX < @x
          @x-=20

        if @lastTouchY >= @y
          @y+=20

        if @lastTouchY < @y
          @y-=20

  return game_screen

There is a lot here, but fret not, all will be revealed.
There is commented line in the render function that we will get back to, where we draw an image from an image sprite to represent the current player.
For now, you will see that we are simply drawing a rectangle at the current point (x, y).
We will update this x, y coordinate by listening to the arrow keys on the keyboard, and we will update the rectangle on screen to reflect the new position.

As explained above, canvasquery simplifies parsing the input for us by allowing us to test for keypresses with concice statements such as:

1
if game.keyboard.keys["right"]

We do not have to deal with character codes.
You will see if conditions in the checkKeyPresses method that test for the arrow keys on our keyboard.
If a keypress is detected, we modify the x, y pair to reflect the direction that was pressed.

You will see that the checkKeyPresses function is called from our step callback which is in turn called once per game loop.

Now, in our render step, we would like to draw the square at the current x, y.

We do this with the following line:

1
game.layer.clear("#7EC0EE").fillStyle("red").fillRect(@x, @y, @x + 500, @y + 500)

This is another handy shortcut for drawing rectangles provided to us by canvasquery.
To do this using a raw html5 canvas would require more fiddly code!
Note, that if you want to access the underlying canvas object or context, you can still do so.

See Here For More Info

You will see that we are drawing a red square of 500x500.
So, in essence, we should now see a square on screen that we control on screen with our arrow keys.
One thing to note is that we do not allow the square to go outside the bounds of the screen.
We do this at the end of the step method, where we simply cap the maximum and minimum values of x and y.

Another thing to note here is that our game is running in scaled mode, scaleToFit: true
Canvasquery is clever enough to scale our input events also when you resize the screen and also when you are drawing something on to the canvas!

So, now we have already hooked up our game screen to our game in the app.coffee file.
This screen will be shown after we click the mouse on the main menu!

You can use the arrow keys to move the square around within the bounds of your game canvas!

For a little extra fun, you will see that we are also responding to touch events.
If you run the app on a touch compatible screen, you will be able to make the square travel to the last point of contact.
The code is pretty self explanatory, it is all contained within the checkTouches method.

So, this is a really simple, lame example of a game you can program using the above technologies, but it serves as an introduction to the possibilities available to you when you leverage the playground API.

We will get on to more complex examples of what you can create in future blogs!

Stay posted!

Friday 6 February 2015

Setting up your project with Grunt and RequireJS

Before we get into the meat and potatoes of our app. We must get the mundane details out of the way.
I would like to dive straight into the graphics and AI stuff, but thought a small primer on getting a nice working environment set up would be worth while in the long run.

There are many ways you can set up your project structure and many ways to host it.

I have chosen to host mine on Heroku via a Ruby On Rails project.

This Rails project will serve up our Javascript application and also may some day serve as a back end to serve data to our games.
I am thinking of using Pusher to share data across devices at some stage, and the Rails application will allow us to do this.

Setting up the Rails app and running it on heroku is outside of the scope of this blog. There are many tutorials online on how to achieve this.

I have included the source code of the project I am working on in tandem with this blog, and will link to the tags where necessary.

Here is the tagged version of the codebase, relating to this blog post.
And here is the current codebase.

See here for an example of the end goal we are trying to achieve


So, now let's get to some coding.


Setting Up Grunt


We will use a Javascript build tool called Grunt to automate some of the tasks required to bundle our code into a runnable application.

I have created a source directory in the rails project root called 2djssrc. This is where our source code will reside. We will rely on some grunt tasks to compile all of our code into the rails public folder which will then be served up to the user. We will also use a Javascript package manager called Bower to manage our Javascript plugins.

To get Grunt set up, you will need to install nodeJS and the node package manager. Here are some guidelines.

These steps will mean you now have a package.json file in your source directory that specifies the node dependencies. This file will list our grunt plugins later on.

Now, our Gruntfile.js is where all the magic happens. This simply contains all of our tasks that will help us to get our code to run.
To run a grunt task, we simply run:

grunt TASKNAME
Tasks can depend on eachother as follows (Don't worry about what each task does right now, the fact is that they can depend on eachother):

grunt.registerTask('compile', ['haml', 'sass', 'coffee', 'requirejs']);
grunt.registerTask('dist', ['compile', 'copy:assets']);
grunt.registerTask('default', 'dist');

If you leave out the taskname, then grunt will run whatever task you have configured as the default. More on Grunt later.


Setting Up Bower


So, we want to use some nice JS plugins. There are so many out there that do great things, so why reinvent the wheel?
Bower to the rescue.

npm install -g bower
This will give you access to the command:

bower install
We just need to tell bower where to install our downloaded plugins.
We do this by placing a .bowerrc file in our project root, with the content:

{ "directory": "src/javascripts/bower_lib" }
Now, let's try it out and install jquery.

bower install --save-dev jquery
You will see the library now in src/javascripts/bower_lib
You can search bower for packages with:

bower search PACKAGENAME
We will use bower to install dependencies needed in our project such as box2d. The source will be included in later blog posts so you will actually not have to run these commands, but get used to the syntax.


Directory Structure And RequireJS


So, we are working inside our 2djssrc directory.

We are going to use Coffeescript to write the our application. Coffeescript will compile down to javascript.
I find it saves a lot of needless typing and has really concise, readable syntax.

Looking at the source, you will notice that there is a directory named coffeescripts and also a directory named javascripts. We will write our code in the coffeescripts directory. We will use a Grunt plugin to compile our coffeescript code into it's associated javascript counterpart, and then we will feed all of that code into another grunt plugin (grunt-contrib-requirejs) that will compile it all into one single file by traversing all of the requireJS dependencies. That was a mouthful! But, really all it means is that we need to do the following (see the github repo for the actual code):

Tell node you want some packages:

npm install grunt-contrib-coffee --save-dev
npm install grunt-contrib-requirejs --save-dev

Now, enable these packages in your Gruntfile.js, by adding the following to the file:

grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-requirejs');

In the Javascripts directory, we see two already existing directories lib and bower_lib. The lib directory contains some Javascript libraries that we could not get through bower. They will be copied into the main js file by grunt once we run the RequireJS grunt task. The bower_lib directory is our bower library repository, where any library we get by running:

bower install --dev
is stored.

To achieve this, we must configure our grunt Coffeescript task to find our Coffeescript files and copy them into the Javascripts directory after compilation. We do this with:

    coffee: {
      options: {
        bare: true
      },
      compile: {
        expand: true,
        cwd: 'src/coffeescripts/',
        src: ['**/*.coffee'],
        dest: 'src/javascripts/',
        ext: '.js'
      }
    }

So, once our compiled js files are sitting in the javascripts directory, we can then run the requireJS task to traverse the dependencies and create one big monolithic file! We must tell requireJS where our libraries are. This is done by creating a config.coffee file and referencing it in the grunt task like so:

mainConfigFile: 'src/javascripts/config.js'
In this file we set up the paths to our dependencies. More on this here. Have a look at the source code again if you are unsure.

We then configure the task, as follows, passing it the entry point file "main" as follows:

    requirejs: {
      compile: {
        options: {
          name: 'main',
          baseUrl: 'src/javascripts',
          mainConfigFile: 'src/javascripts/config.js',
          out: '../public/javascripts/main-built.js',
          optimize: "none"
        }
      }
    }

The way the above works is that it looks for the file main.js in the "baseUrl" directory. This file, you write yourself, and it is the entry point into your application.
It will load all other required files using the following syntax:

require([FILELIST], function(DEPENDENCIES){})
Read the requireJS docs for more on this.
Common practice is that main.js will be the entry point into your application.
From there app.js will be called, which contains your application logic.
If you look at the source, you will see that our app, at the moment simply alerts a message to the screen. Ground breaking stuff!


This is not all grunt can do.
We can use it to clean up compiled JS files in the javascripts directory that are no longer needed after compilation.
We can use it to copy over assets or any other files to other destinations in our project.
Furthermore we can run a watcher task that reloads our browser when a file changes. More on this later!
So, if you run the grunt dist task in the included project, you will see a file in the public/javascripts directory called main-build.js which includes all of our source and any included libraries we need.


HAML/SASS And Serving Up Our App


Ok, so we now have two grunt tasks which get us from a bunch of coffeescript files to a monolithic javascript file. What next?

Well, there are some libraries we need that we have to include manually.
I have manually included the requirejs library for now as I had some complications with referencing it from the html.
There is a directory in our source directory called lib. This contains any other libraries we need outside of the requirejs compilation.
We'll we use a grunt task to copy any files in this directory to public/javascripts/lib to be easily referenced.

We have to somehow serve up our app on a web page.
I like to use HAML to write my HTML, but it requires some setting up.

Again, grunt has a task for this: https://github.com/jhchen/grunt-haml2html
We create our index.haml file in our 2djssrc directory and use this plugin to compile it to public/game.html.
If you look in the index.haml file you will see that all it does is reference a file "requirejs" and also has a data-main attribute in the script tag which is used by requireJS.
This attribute must point to our fully compiled JS file from the previous grunt task.

<script data-main='javascripts/main-built' src='javascripts/lib/require.js'></script>
Note that you must install the haml gem for this. It is already included in the Rails app Gemfile, so a simple bundle command will solve this.

One last thing is that I will also use the grunt SASS plugin to compile some SASS files down to CSS. The idea is basically the same as what we did for the coffeescript files. Take a look in the source to get a better understanding.

In theory, this is all we need to get going. If we view our compiled game.html (via the /game url in our rails app) page we will hopefully see the alert message showing up.

It seems like a lot of work to get all this set up, and yes, it is a very steep learning curve.
However, once you have mastered these steps, you will benefit from fast development and modular javascript.
It will allow us to concentrate more on our application logic rather than where stuff should go.
Grunt will serve us as a great tool to automate a lot of things as we progress, so read up on it.

Hopefully, you got something from this tutorial, and it won't be long before we get into some of the good stuff.

Stay tuned!

Thursday 5 February 2015

Do we really need a native app?

As with most adolescent males, I have always been into gaming, having owned an Amstrad at 6 years old, wasting hours playing games like bomb jack. We all remember waiting for what seemed like an eternity on those old tapes to load!

Gaming intrigued me more so because I was curious as to the inner workings and mechanics that drove the games.

I wrote an essay back in college, on the history of gaming, and it was fascinating to me just how far it had come in the mere 30 years since its inception. I always knew that it would be an industry that I would love to work in. After a few years of working in web development, I decided to dive deeper into the guts of gaming, in an attempt to vary the work I was doing. Mobile gaming always stood out to me a bit more, as it seemed like an easier market to penetrate, and with the advent of smart phones and developer programs for iOS/Android, it lowered the bar for developers to get their work out there. I decided to research what was actually required to get a game to the app store.

So, did I want to build an native iOS game?

I had done some C/C++ in college, but having worked with Ruby On Rails and front end JavaScript frameworks (EmberJS, Backbone) for quite some time, I found that taking the leap back to these type of languages would only slow me down, or at least initially during the steep learning curve. I did not really feel the drive to learn either objective C or the new Swift programming language that will eventually take over the apple ecosystem. I thought that I might as well try to harness the skills I have at hand. Also, if I the game was to run on the android platform, I would have to port the code to Java and use the android SDK. Not so much fun!

Enter Phonegap, or now as it is known: Cordova. Cordova is a great little piece of software under the Apache licence that allows you to write a HTML/Javascript/CSS application (using any of the previously mentioned JS frameworks) and then simply build a native version of your application for multiple platforms such as Android/iOS/Windows Phone etc.

It all sounds too easy, right?
If you plan on writing a really heavy duty blockbuster 3D game then you might want to consider writing a native app, as with the performance of a native app over an app built with Cordova, there is simply no comparison.

For simplicity sake, however, I am going to stick with writing a simple 2D game from scratch. Well at least at first, and then include a 2D Javascript physics engine known as Box2D to do some of the heavy lifting. I will start from scratch with some simple animations and x/y coordinate manipulation so as to give you a better understanding of what the physics engine is actually doing for you once we hook it up! We will tinker with a framework called CanvasQuery which is a simple JS library for controlling your game run loop. This will allow you to read some input from the mouse/keyboard and control an on screen character, essentially creating a really simple game.
Once we have this up and running I will show you how to use Cordova to translate the game to an installable mobile app. I will show you how you can read from the devices sensors (Accelerometer), via the Cordova API.
Then we will dive into some really interesting stuff, and what I find most interesting in Computer Science. Artificial Intelligence. I will introduce some AI concepts into the games, such as hooking up a neural network to control other players.

This blog assumes some knowledge of HTML/Javscript/CSS and also some JS tools such as Grunt/RequireJS/Bower, but if you do not know these technologies too well, fear not. Our primary focus here is on the gaming side of things!

Knowledge of Vector maths might also be a bonus when we get into some more advanced graphic rendering and line of sight algorithms, but again not essential! I will link to the Box2D docs and any other required documentation for any plugins/frameworks I bring into the mix!

By the end of this, I hope to have a fairly playable mobile game written in Javascript that utilizes some sort of AI that performs reasonably well on a standard mobile device. It will never be as sharp as it's native counterpart, but for the simplicity and effort involved, I think that this route to creating a mobile game should be something you consider!

If you want to see a live demo of some of the things I have been playing around with, see:

http://canvasgames.herokuapp.com/game

Stay tuned!