How to Make a Platformer Game with Cocos2D-X

Animation & Spritesheets

A sprite is a single graphic image. It can be moved around the screen, stretched, rotated, skewed, faded and tinted.

A single sprite

A spritesheet is a collection of sprites into a single texture file. This makes it easy to animate a single sprite by changing the sprite's displayed frame in sequence over a specified duration. Just like a movie reel, a spritesheet can create the illusion of motion.

A basic spritesheet

A benefit of packing your sprites into a spritesheet is that you can really optimize the texture memory required by your game. Extra spacing around your sprites can be automatically trimmed from the texture and then re-applied when loaded into an actual sprite. Rotation can be applied to the sprites so that more of them fit neatly into the texture. Compressed image formats can be used to further increase the speed and efficiency of your game. See how tightly packed these sprites are?

An optimized spritesheet

In this chapter, we'll make a ninja spritesheet and then learn how to use it in your game.

The Ninja

A ninja sprite

The first step in making a spritesheet is deciding what sprite frames you want to include. In the case of a platformer, we just need frames of the ninja running and jumping to the right. We can flip the right-facing sprites over the x plane to create left-facing sprites.

For the running frames, we'll use ninja-running-e0000.png through ninja-running-e0007.png. For the jumping frames, ninja-sidekick-e0000.png through ninja-sidekick-e0012.png. We'll throw in a few standing frames too: ninja-stopped0000.png through ninja-stopped0003.png.

Three Tiers of Art

These days, it can help to produce three tiers of art assets: SD, HD and HDR (HD Retina). The SD assets are used for older devices like an iPhone 3GS with a screen resolution of 480x320. The HD assets are used for devices with a screen width greater than 959 pixels, for example the iPad 1st generation at 1024x768. The HDR assets are used for devices with a screen width >= 2000 pixels or so, i.e. the iPad 3 at 2048x1536.

How does one create so many art files? Easy. Just create the art at the highest resolution (HDR) and then let the spritesheet maker scale it down for the lower tiers (SD and HD).

By taking the original SD ninja, scaling him up to HDR resolution and using a bit of median blur, we can create a decent-looking HDR sprite.

An HDR ninja sprite

I made a folder with all the sprites I wanted to enhance, then created a Photoshop Droplet to process them all at once.

The Droplet applies a color range to get rid of the brown background color, then another color range to remove the shadow. Next the Droplet sizes the image to 400% with Bicubic Smoother image resampling. Finally, a 3-pixel Noise > Median is applied and the file is saved and closed.

Here's a zip file of the completed HDR ninja sprites.

Spritesheet Makers

A spritesheet maker takes a group of sprites and packs them together. In this tutorial, we'll use Texture Packer. Alternatively, you could use Zwoptex.

Open up TexturePacker, click the Add Folder button and select the Ninja-HDR folder. This adds all the ninja sprites to the sheet.

The ninja spritesheet

Next we'll give the spritesheet settings to ensure it creates an optimal texture, then publish it.

Spritesheet Settings

Spritesheets are composed of a texture file and a data file. The texture file is an image (for example, a .png) and the data file is a property list (.plist) with information about each sprite frame contained in the texture.

Let’s tell TexturePacker where to export the texture and data files. Simply click the folder / “...” button next to Data file and browse to the folder where you want to save. Keep in mind that you'll want to create SD, HD and HDR folders for your game's art asset tiers. So create a folder called "HDR" and then save with the filename "Ninja".

TexturePacker will automatically add the .plist extension to create Ninja.plist and set the Ninja.png texture file as well.

Texture Packer editing the ninja spritesheet

The PNG texture format, however, is uncompressed. To help your textures load faster and consume less memory, we'll use the "zlib compressed PVR" (.pvr.ccz) format. Choose it from the Texture Format drop-down. Older versions of TexturePacker might give you a warning about setting PVRImagesHavePremultipliedAlpha:YES in your code. Just click Ignore.

Check out how much memory your sprite sheet will consume when it is loaded as a texture. You can see this number in the bottom right of the TexturePacker window. It will say something like “Size: 1024x1024 RAM: 4096 kB.” Let’s see if we can decrease that texture memory usage.

Image Format

You’ll see underneath Texture Format we have Image Format. It defaults to RGBA8888, which uses 8 bits per channel x 4 channels (red, green, blue and alpha).

Open up the Image Format drop-down and try some other options. Watch how each format affects the spritesheet’s memory usage. The preview will change to show you approximately how it will look in your game.

When you change the image format away from RGBA8888, your image quality might start to degrade a bit. To get it looking right again while still using the more memory-optimal image formats, you can try a few of the Dithering options.

Set the Image Format to RGBA4444 and the dithering to FloydSteinberg+Alpha. These will give you textures that still look about as good as RGBA8888 yet use half the memory. Your size indicator will now say something like “Size: 1024x1024 RAM: 2048 kB.”

All the other settings should be good by default. Feel free to play with them and watch how your spritesheet is affected.

Publishing the Spritesheet

Now that you've got the settings straight, click the Publish icon. This will save your HDR/Ninja.pvr.ccz and HDR/Ninja.plist spritesheet files. But what about the SD and HD versions?

Click the AutoSD button and apply the "cocos2d-X HDR/HD/SD" preset. Next, replace "HDR" with "{v}" in the Data file and Texture file. When you go to Publish, it will automatically create a 0.5 scale sheet in your HD folder and a 0.25 scale sheet in your SD folder.

You now have an SD, HD and HDR folder with an appropriately-sized Ninja.pvr.ccz and Ninja.plist in each folder.

The completed Ninja folder of SD, HD and HDR spritesheets

Your final TexturePacker file will look something like this:

The completed Ninja TexturePacker file

Using Spritesheets with Cocos2d-X

So how does one use a spritesheet with Cocos2d-X? The first thing you've got to do is load the texture file and cache the sprite frames:

// set the appropriate resource directory for this device
FileUtils::getInstance()->addSearchResolutionsOrder("HD");

// load and cache the texture and sprite frames
auto cacher = SpriteFrameCache::getInstance();
cacher->addSpriteFramesWithFile("Ninja.plist");

Here's how to create a sprite using one of the sprite frames:

Sprite* someSprite = new Sprite;
someSprite->initWithSpriteFrameName("ninja-stopped0000.png");

To individually get one of the sprite frames:

// get the sprite frame
SpriteFrame* frame =
  cacher->getSpriteFrameByName("ninja-sidekick-e0007.png");

// set someSprite's display frame
someSprite->setSpriteFrame(frame);

To play an animation:

#include <iomanip>

// load all the animation frames into an array
const int kNumberOfFrames = 13;
Vector<SpriteFrame*> frames;
for (int i = 0; i < kNumberOfFrames; i++)
{
  stringstream ss;
  ss << "ninja-sidekick-e" << setfill('0') << setw(4) << i << ".png";
  frames.pushBack(cacher->getSpriteFrameByName(ss.str()));
}

// play the animation
Animation* anim = new Animation;
anim->initWithSpriteFrames(frames, 0.05f);
someSprite->runAction(Animate::create(anim));

That's it for the code examples. If you'd like to see what else you can do with a SpriteFrame, just open Xcode, hold the Command key and click on SpriteFrame. You'll be taken to the SpriteFrame class interface, where you can peruse the methodology.

Conclusion

That's all for this chapter.

Paralaxer with a ninja

Got questions? Leave a comment below. You can also subscribe to be notified when we release new chapters.

Next Chapter >

Comments


Comments
  1. David

    Cool article!

    It may be helpful to add a delay between animation frames. The ninja animation wasn’t visible for me until I tweaked the initWithSpriteFrames call:

    anim->initWithSpriteFrames(frames, 0.05);

    • Nat Weiss

      Thanks! Updated the chapter with your suggestion.

  2. Christian Feldbacher

    Hi,
    great article!

    With V-Play, we do apply a similar approach to the one described by you here. To support all kinds of aspect ratios and screen resolutions, we also use content scaling and bigger backgrounds to avoid black bars at non-3:2 ratios. You can have a look at the description of our technique here:
    http://doc.v-play.net/beta/vplay-different-screen-sizes.html

    If you don’t mind, I would love to link this blog post at the “useful links section” in this site.

    Looking forward to the next posts already & thumbs up for your good work,
    Chris

    • Nat Weiss

      Hi Chris, nice article. The list of aspect ratios is quite handy. And yes, feel free to link to this article.
      Nat

    • Tim

      Hi Nat,

      I was wondering what your thoughts were on the max dimensions for a sprite sheet? Would you recommend 1024×1024 for entry level phones or would you suggest lower/higher dimensions? Would you suggest the same for mid-level phones?

      I was also wondering what background sizes you recommend for SD, HD and HDR? Would you agree with Christian’s posted article to go with the sizes 576×368, 1152×736 and 2304×1472. I am using cocos2d-x multiple resolution support (http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Multi_resolution_support) for displaying my artwork if that makes a difference.

      Thanks in advance
      Tim

    • Nat Weiss

      Hi Tim,

      First, you’ll really want to set some target devices you intend to support. This will help immensely to give you some peace of mind.

      If you want to support older or non-retina phones then stick with 1024×1024 as the max spritesheet size for your set of SD graphics. 2048×2048 is a good max for HD and 4096×4096 will suit HDR.

      As for background sizes, those numbers sound fine. Just remember to design your background art so that the edges don’t have any important info or graphics so they can easily be cropped.

  3. AK

    Hi guys. Just found this article as I’m looking to start using TexturePacker; great work. I have one question which might be more Cocos2d-x related but I’ll ask anyway. If I wanted to use a graphics set like HD, but scale it a little to fit the device screen dimensions dynamically (On a PC or Mac for instance) in a resolution independent way, can Cocos2d-x support that with TexturePacker files? Is it just a scale factor of some sort that I can apply to everything?

    • Nat Weiss

      Yes, you can easily scale any Cocos2d-X node with the setScale() function.

      Or you can use the overall setDesignResolution() function to apply scaling to the entire screen.

      So you set tour spritesheet however you want it in TexturePacker, then dynamically resize with Cocos2d-x.

  4. Stu

    A bit cheeky, but… would be very cool if you could show a port of this to cocos2d html 5 :)

    • Nat Weiss

      Yep, that’s on my to-do list. :)

  5. Mackie

    Great tutorial! One thing to point out about the use of setResourceDirectory for setting the resource directory. As this is deprecated now, you should update your tutorial to use setSearchPaths instead. Cheers.

    • Nat Weiss

      Updated, thanks.

  6. Mikey Aburamadan

    “No member named ‘setResourceDirectory’ in ‘cocos2d::CCFileUtils’ ”
    What do I do about this?

    • Nat Weiss

      The function name has been changed. Open up CCFileUtils.h to double check, but I think you can now just use setResolutionsOrderDirectory (something like that).

  7. Wassim

    Hi thank you for this post
    I create a new sprite sheet for my game but the problem is i dont know why new sprite appear inverted in the screen ??

    Please help

    • Nat Weiss

      Sounds like it’s probably a problem with the spritesheet. Can you try disabling rotations and see if that fixes it?

  8. mat

    Nice article! But some error occurs:

    Got a question belonging the running animation. everthing worked fine with the animation except of the ending: I used the repeatForever function when a touch is started, when the touch ended, I tried to stopAllActions() which ended with the current animation sprite (but the character shouldnt freeze, the animation should be applied one last time and than resume to the beginning sprite image).
    and heres the next error: when i’m changing the sprite image after a animation (even if it is ran one) the image looks like its scaled, but the sprite isnt scaled. any help?

    • Nat Weiss

      Mat, stopAllActions() is meant to immediately stop any running actions. If you want the animation to be applied one last time then you’ll have to call stopAllActions() after it has fully run the animation or call stopAllActions() and then runAction() with one final animation. The other option you have is to not use CCRepeatForever() but CCRepeat() with a finite number of animations.
      In regards to your other question about the sprite looking like it’s scaled, this might perhaps be a spritesheet issue? It’s difficult to tell without seeing a screenshot.