Introduction to enchant.js: part II

Hi!, since there is quite a bit to tell in today’s post I will go straight to the point!, let’s pick up from where we left of on the first part of this tutorial.

As with everything in life, first things first: we are going to need some art for our game.

In order to get moving quickly we are going to use some graphics I already made for this tutorial, but if you are curious on how to make your own assets (and if you are here it probably means you are) don’t hesitate and go check our pixel art tutorial right now!

Back to our game.

As I said, we are going to make a Flappy Bird clone, so we are going to have our player flying around trying to avoid an infinite swarm of green Mario-like pipes. Our player, won’t be a bird this time but this happy fellow:




First, we are going to use the physics simulation box2d provides in order to have our cat hit the floor and pipes in a realistic way. We will also have gravity, that will pull the player down to the ground and an upwards impulse to push the cat into the sky every time the player clicks on his mouse (or taps on the screen).

To achieve this, we have to create and initialize a PhyisicsWorld variable in our GameScene initialize method, like this:

physicsWorld = new PhysicsWorld(0, gravity);

(remember to declare the “var physicsWorld;” before the window.onload declaration to make it a global scope variable).

Now, on the onenterframe method of GameScene we will evaluate every collision and interaction between elements that “live” inside the world by doing and update on each frame, like so:

Captura de pantalla 2014-05-04 a la(s) 20.48.09

With this done, it’s time to create our game objects. As we saw before, enchant.js works with classes, so in the same way we did with our GameScene we will create a Player class, with its own methods: initialize and onenterframe.

The player class will look like this:

Captura de pantalla 2014-05-04 a la(s) 21.03.22

As you can see this class extends the PhyBoxSprite class, which allows us to have sprites that are able to intract with a PhysicsWorld.
Notice that we create the sprite with the enchant.box2d.DYNAMIC_SPRITE parameter, so our sprite will react on every collision with another physic object in a way that it will be affected by gravity and outside impulses.
Then, we initilize the sprite’s graphic asset and initial position. We also use an internal variable, called animationDuration which will keep track of the time that has passed since the last animation was used, so we can know when to step to the next frame of animation, as we will now see on the onenterframe method.

On every frame we check how much time has passed by updating the value of animationDuration. When a specific value is reached (0.1 in our game) we step the animation to the next frame. We only have four frames on our player’s spritesheet so we will use the mod (%) operation to cycle around every one of them.

Next, we set up the Block Class in a similar manner:

Captura de pantalla 2014-05-04 a la(s) 21.03.28

As you can see we have 3 types of block sizes 120px, 165px and 210px, so we can create a block with it’s related sprite depending on the size we want to use. Also, we create their physic body as STATIC, so it does not move when another object collides with it.

In this case we won’t animate the blocks, we just want them to move left, so on each frame we will decrease their x position by a specific value that we will call “blockSpeed” (appropiate, isn’t it?).

Now that we can create our game objects it’s time to put them to good use. Inside our GameScene’s initialize method we create and initialize our player variable, as well as the background image background and the scrolling floor (which will also be a PhyBoxSprite, in order for it to “interact” with our flying cat). We also create a pool for blocks. This is a variable that can hold objects in order to be able to work with them in a easy way.

Using groups we can easily access a whole set of game objetcs and then apply a specific method to them in just one sitting (things like moving them at the same time or even removing them all). This time we just need our blocks to be accesible and removable quickly, so we will group them all together and update them all on every frame.

Captura de pantalla 2014-05-04 a la(s) 21.19.21

You might have noticed that we add one background or another depending on a random number. One of them is a day bg and the other one a night bg, so it will give the game a different look every time you die and have to restart it (which will happen A LOT).

We also set up and event listener to the touchend event, which means that whenever the user clicks (or touches the screen) this will fire up. More on that later.

Once this is done we just have to append all this elements to our game class, like so:

Captura de pantalla 2014-05-04 a la(s) 21.27.25

We also set up the variable that will keep track of the time passed since the last time we spawned a new block. Since we are initializing the game we set it up to 0.

At last, we get to where the magic happens, the GameScene’s “onenterframe” method. This is just the update method for our game, so we will have to check for the state of every object and update them accordingly.

Captura de pantalla 2014-05-04 a la(s) 21.29.24

First we check  if the player is contacting something. This means that it’s physic entity is colliding with another one of the blocks or with the floor. When this happens we just stop the game (if it wasn’t already stopped) and play a nice and loud crashing sound.

Just below, we simulate our physics world on each frame, allowing us to update object positions when they are affected by gravity and other impulses.

Captura de pantalla 2014-05-04 a la(s) 21.40.04

After this, and only when the game is being played, we update the scrolling floor’s position to give the effect that we are advancing forward.

Below is the block generation code. Every time the spawnBlockTimer reaches a certain value the game generates a new block, randomizing its generation so the game keeps up challenging. Finally, we check when a block has left the screen in order to remove it from the scene, so we don’t have unused objects out of scene that take up resources and eventually slow things up.

And, at last we code up the game’s reaction to player input:

Captura de pantalla 2014-05-04 a la(s) 21.45.52

As you can see, it simply applies upwards impulse to the player if the game is in PLAYING state, otherwise it just either waits for the first user input (the game does not start until the player clicks) or checks for player input after the game has finished (the player must click again to restart). When this happens the game just reinitializes everything by destroying the physical entities of every object and then destroys the scene, creating a new one starting the game over again.

And that’s basically it!, you can now play our flappy clone here.

Captura de pantalla 2014-04-21 a la(s) 21.31.14

And you can download the full code and assets for it from here.

Of course, feel free to modify it anyway you want and don’t hesitate to show us your results!


Introduction to enchant.js: Part I

Playing games is cool. Making them by yourself is cooler. But being able to make a pretty decent game in a few hours and then sharing it with the world in just a few clicks is the coolest thing of them all.

That’s what HTML5 gaming empowers us to do. Using your web browser as a gaming platform you can get your gaming fix wherever you are, without having to worry on hardware, performance o even needing to download a single file into your device.


A few years back when Flash was the “best thing to ever happened to the internet”, you could see animations, games or even movies made with it all over the place. A few years later, with the progressive withdrawal of Flash support on various platforms and devices and the advent of Javascript, HTML5, CSS3 and a few other technologies things have changed quite a bit.

Some people see the demise of Flash as a backwards move, since it allowed people with little programming background to easily create interactive software for the web in a short period of time. They may be right, but if you are here reading this you won’t probably have those problems in the first place (you geek!).

Lucky you, because on today’s tutorial we are going to take a quick look on how to make a canvas-based HTML5 game from scratch!

There are many ways to start coding HTML5 games. Some people just use plain javascript and use the DOM elements to make objects and animations. Others will use a various array of plugins to display graphics on screen. Some will even end up using SVG elements to create a complete game. All of those approaches are ok, but since HTML5 introduced the <canvas> element it has all been a lot more coherent and comprehensive to use for us game developers.

It allows us to have a sort of drawing board, where we can render things in 2D/3D in the same way you would do in a more traditional platform. You can also benefit from the hardware acceleration capabilities of each device  since it supports the WebGL standard for rendering. At this point we could start coding up our game with javascript and manipulating the <canvas> element to make it a reality, but you would end up realizing that it is not exactly what would you expect from a game engine. Mainly because it isn’t one. Things like game flow, sprite manipulation or animation are still up to you, so you’ll end up writing a lot of code in order to be able to do some very basic things.

That’s where Javascript game engines come in. They add an abstraction layer on top of the <canvas> element, allowing you to interact with it in a more intuitive way for game developers, filling in the gaps with functions and methods that allow us to do what we really want without having to waste time reinventing the wheel or making our own sprite management methods, for example. There are TONS of different javascript game engines out there. Some are better than others, some are free and others are not. Some even have interactive editing tools for levels and such. Before you start coding anything I would recommend on spending some time testing a few ones and seeing what each is capable of.

Introducing enchant.js


For the purpose of this tutorial we are going to be using Enchant js. It is a lightweight 2D/3D engine with a huge japanese company behind but it is free to use (MIT License, YAY). There is a live community supporting it and most importantly,  I’ve found it to be one of the cleanest and simplest js game engines out there. It’s really easy to use and you can get you game up and running in a few minutes, which is what we are about to do now.

  Setting up the environment

Since it is a web game and we will probably want people to be able to play it online at some point we are going to create a test server environment where we can place our files into a folder in the same way they will end up in our production server once the game is finished and published. For this purpose I use XAMPP . It sets up an Apache server in a few clicks, with a simple GUI to turn ON or OFF each of it’s components. It rocks.

(Of course if you already have an Apache server -or equivalent- installed just skip this step, duh).

We are going to create a separate folder with the following structure:


index.html – the webpage from where the game will be loaded and played.

css/game.css – css file to customize that page if we want, but it won’t have much content in this tutorial.

res/ – folder where we will store our sprites, graphics and sounds for the game.

js/ – folder where we will store our game code. As you can see we have the main enchant.js plugin as well as some plugin files to use some extra functionality for our game (more on that soon).

js/main.js The main code file for our game, that’s where the “magic” happens.

Running the game

Once this is done we will need to set up our index.html as follows:


As you can see we just included the needed js and css files and created an empty body element. Then, we just create our main.js file, like so:


Now you can access the index.html file from your web browser and you’ll get a blue screen. Still nothing fancy but we will get there. Before moving on let’s see what the current main.js code is doing:

1.- First, we call enchant.js. This will initialize the plugin for us to use and it will also create a canvas element inside our DOM for our game to live in.

2.- We define some global variables, in this case it is just the screen size we want enchant.js to generate for us in the next step.

3.- When the page has loaded completely (i.e every js, css, or /res file have been downloaded to the client) we start running our code.

4.- We create a new game variable with a given height and width. Once that’s done we configure the game to run at 30fps and to have a scale of 1 (using a higher number will multiply the screen size by that number, and enchant.js will resize the viewport accordingly).

5.- We set up an onload method for the game variable that will only instantiate a new GameScreen class. With that done we just call the start() method of our game variable in order to get the game running.

6.- Below that we can define every class we need for our game (players, enemies, bullets, scenes and so on). In this case we only have the GameScene class which inherits from the enchant.js Scene class, so it will behave as a normal Scene but it will perform our specific game logic.

7.- This GameScene class currently has only two methods. THe first one, initialize() will be called when the scene is created and it will prepare everything it needs to run. For now it just calls the default scene constructor and then sets its own background to a blue color.

As you can see with only a few lines of code we have the engine running with our first scene, which -for the moment- just tints it’s background with blue. With all the groundwork done we can now start thinking on what our game is going to be.

I’ve been thinking on doing a Flappy Bird clone myself for a while, not because I like the game or anything of the sort, but because I have been wondering how difficult could it be to make it (not much) and because I wanted to test out the enchant.js implementation of Box2D, which as some of you may know already is a physics simulation engine for 2D games.


In the next part of this tutorial we’ll develop the core game logic, where we’ll take on matters such as sprite drawing and animation, physics interaction and user input. Oh, and we will also see a practical implementation of parallax backgrounds!

That’s all for now, stay tuned for the next part of the tutorial!

P.S- BTW, the next Ludum Dare is taking place next weekend, we may take part on it so keep an eye on our Twitter account for updates 🙂