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:

 

player

 

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!

 

Getting started with Pixelart

Pixel art and indie video games: the return of the pixel

Some years ago, when 3D games shone running in the brand new 32 bits consoles,  2D graphics with low pixel density was considered by most gamers as something from the past. Polygons replaced pixels in most of those new games, or at least, the designer increased the pixel density, hiding those squared forms and hard edges from the past. With the indie wave, games like “Gods Will Be Watching”, “Hotline Miami” or “Fez” gave pixel a new dimension, showing a new way to show an entire world to players using pixels, without  heavy textures and 4 million polygons for each model.

pixel art example

pixel art example

In my case I love how games like “Fez” looks, but I’m not a big fan of designing using pixel art. The main reason is because among video game development beginners there is a general belief about pixel art being an easy (or the easiest) and fast way to create game assets. In my opinion, creating some basic pixel art assets is quite easy, but if you want something good, it becomes a frustrating work, painting pixel to pixel by hand in most of cases, frame by frame of each animation without any interpolation tools or ridges. It may seems as easy as composing something using little colored squares, but there are techniques, processes and problems you should know before jumping into a project with thousands pixels to paint.

How to get started?

After trying to draw something using a 16x16px canvas, some may think about drawing something in a large canvas and then reduce the image size to 16x16px. It’s a good approach, but even using a software like Photoshop with some configuration parameters optimized for reduction, the result won’t be as good as a handmade pixel art could be. If you want to give it a try, in Photoshop go to Edit-> Preferences -> General ->Image Interpolation -> Bi-cubic Sharper, and then resize your image to a few pixel canvas. You’ll have something like this:

pixel art by reduction problems

pixel art by reduction problems

The automatic interpolation will end with blurry lines, loss of detail and some colour problem as can be seen above. The real sized view it’s more or less well defined, but we want a model with noticeable pixel composition, not a smaller one. As I told, a good pixel art piece is far from done by a few clicks, but this process is a good starting point for future steps.

Drawing with pixels, dithering and pixel over

Ok! Open your favourite drawing software, create an small squared document (like 16 or 32 pixel per side) and look for a tool that allows you to paint only one pixel at a time. In Photoshop, the pencil tool is the way to go. Try to draw something and you will notice some difficulties drawing diagonal lines and curves. At this resolution, each pixel will be visible and a curve and a diagonal line are impossible to be represented as a composition of little squares like the pixels are. They should be represented by approximation, drawing pixels in a zig-zag pattern  to fit them to what we want as much as possible.

basic pixel art lines

basic pixel art lines

 

Leaving lines aside, any area can be filled with any available colour by drawing pixel by pixel, but what about transitions between colours? How can we blend a highlight with the base colour? Well, we can’t, at least not how it’s done in high resolution. Again it have to be represented as an approximation called “dithering“, placing pixels of the first colour between pixels of the second one. This won’t be the best solution with every colour palette, giving a weird look for the dithered area if the two colours are complementary or the contrast between them is high.

Dithering examples

Dithering examples

 

Now, going back to the first part of this article, let’s rescue our little cat and resize him. As shown before, the resized picture has some defects, but can still be a great guide to draw the cat by hand. This is called “pixel over”,  and you can resize any picture to draw over it or sketch what you want to create in high resolution and then and use it as a guide after being resized. A fast example can be seen before; even with some outline and dithering errors it’s much better than the automatically resized version seen before.

pixel art fast example

pixel art fast example

Final tips

There is some things to take in consider about pixel art and how to work with it:

  • First of all, never ever save your pixel art works using jpg/jpeg. The compression will change some colours and the final result may change. Its better to store pixel art using gif or png formats to avoid surprises.
  • Use painting tools with 1 pixel radius and without dynamic opacity.
  • Once finished, a pixel art picture is still so small and surely out of scale in your game. To increase it’s size in Photoshop, go to Image -> Image Size and set the desired size and be sure to select “Nearest Neightbor” or your resized image will get blurred.

There are some links if someone want’s more:

Next time the pixel will move! stay tuned.

2D animation. Creating sprites from scratch

Two weeks ago, in my latest post,  I mentioned a list with some things I wanted to know about. One of these things was 2D animation using sprites, and the way I did it may not be the most optimal and easy way to do it, but for once I did it from scratch, by moving every part of the character by hand and redrawing what was needed frame by frame. On the other hand I can say every animation I worked on wasn’t very complicated, mainly due to the short time available to finish them.

Some theory
There are some things you should know before start moving arms and legs. Your game will update the screen several times per second, based on the machine specifications where it’s being executed. This is called framerate, and since it is not equal between machines, a fixed time between tour animation frames will be needed. If you update your animation on each game update, your animation will show faster than light in newer machines and slower and sloppy in the older ones, even if the machine’s hardware is enough to run your game. In my game this is implemented with a constant called “millisecondsPerFrame”, which stores a fixed time in milliseconds (200 in my case). The game will update the screen as fast as possible, but the animation frame won’t change until the actual frame has been active for at least the time stored in that variable.
This amount of time is the base for your animation, every frame should be designed to be active that amount of time, and changing it while creating your sprites may end up with huge problems. The best way is to test which framerate fits your game using prototype textures and animations, and once it’s done, leaving the constant unchanged during the whole development. It’s the Holy Constant that rules your game graphics!

mannequin

Animation test mannequin

 

Another topic to keep in mind while animating a model is how many frames we should create. In my case I always try to create as few as possible. You should create a frame for each noticeable change in the model, considering how it should feel: for a smooth transition, it’ll need more frames, while a sharp one could be done by a few.

For example, if we’re animating a bouncing ball, we can choose from a slower and smooth animation or a fast and sharp one only by creating four frames more for the slower one:

Smoother ball animation

Smoother ball animation

Faster ball animation

Faster ball animation

 

 

 

 

 

 

 

 

Let’s move it

For this project I created every frame from scratch, using only Photoshop as main tool, even though this may not be the faster and optimal way to work. I haven’t tried any other alternatives like 3D flats with textures in 3D software like Blender or Maya. Feel free to make a comment with your thoughts about any other 2D animation process you know! maybe I’ll learn about it for the next project.

The first step is drawing the full character in a base state. He can be as complex as you want for your game, using vector graphics or maybe pixel art, but in case your choice is not pixel art, try to create your base character in a document with a high pixel per inch rate and a good size, as much as your computer can handle.

A little ninja in a pink pyjama!

A little ninja in a pink pyjamas!

Yeah! you have your main character yet? Time to slice him into pieces! That may hurt a bit, but it’s going to make everything easier from now on.

Make some cuts on your character’s joints and give some space between them. There are several tools to achieve this in Photoshop, like the lasso tool, or the ellipse marquee tool, but in mi opinion the pen tool is the best option. Check this link if you want to know how it works: Pen tool tutorial!

Sliced ninja in a pink pajama!

Sliced ninja in a pink pajama!

 

At this point you will be in need of a huge amount of patience. For each frame you have to move every part of your character to the correct place, and sometimes, redraw every joint that not fits well. Your character sheet will need 40 frames? well, you just need to create 40 different puzzles using the slices as pieces. I told you, patience is the key to success.

If your Photoshop is not so old, you can use the timeline feature through the Window menu -> Timeline. You’ll see a frame where you can create frames and play them, which is a useful tool to test your process and tweak every position without getting the texture into your game. Here is a timeline tutorial if you’re having problems dealing with it.

Once you have every frame, you’re almost there. Put every frame in a sprite sheet. I’m usually using a grid, mainly because it’s easier to code, but there are some other options that optimizes the document sizes but makes it hard to code, like the angry bird example:

optimized sprite sheet example

optimized sprite sheet example, all rights owned by Rovio Entertainment Ltd

one row grid spritesheet example

one row grid spritesheet example

 

And there it goes! Your spritesheet is finished and ready to be included in your project. As I said earlier, this way may not be the faster way, and there are some tools that may help you at some point:

See you in the next article and feel free to share what you want with us!