2012年2月4日星期六

How To Build a Monkey Jump Game Using Cocos2D, PhysicsEditor & TexturePacker Part 1

How To Build a Monkey Jump Game Using Cocos2D, PhysicsEditor & TexturePacker Part 1
This is a post by special contributor Andreas Loew, the creator of TexturePacker and PhysicsEditor.

In this tutorial, youll learn how to make a game about a monkey having a rough day. He’s just minding his own business, but these crazy objects keep falling from the sky!

To see what I mean, check out this cool video:


By the end of this tutorial, you’ll have created a cool physics enabled game, and learned how using TexturePacker and PhysicsEditor can save you a ton of development time.

To go through this tutorial, you should have some basic familiarity with Cocos2D. If you are new to Cocos2D, check out some of the other tutorials on this site first.

You will also need a copy of TexturePacker and PhysicsEditor. To to through this tutorial you can use an evaluation version from TexturePacker.com and physicseditor.de, but note that there are some features that are not present in the evaluation versions. If you want to order the full versions, here’s a direct link to order the bundle.

Ready to make that monkey jump? Keep reading to get started!



Getting Started


We will start with the design phase. So let me give you a brief overview of how the game will work.

As you’ve seen, our main character will be a monkey. His movement will be controlled with the accelerometer – that is, by tilting the iPhone or iPad left and right. The monkey will jump when the screen is tapped.

During the game, items will drop from the top of the screen, and the dropping frequency will increase the longer the game continues. We will have a drop indicator to show the player where the next item will fall. Items pile up, and the monkey must stay on top to stay alive.

There will be two sorts of items: those that hurt the monkey, and those that heal him – namely, bananas! The monkey’s health will be displayed in the top-left corner as a bar of bananas.

The score will be displayed in the top-right corner, and will be at the height of the highest item on the stack.



To get started, download the tutorial source code and unzip it into your preferred location. Your starting point will be 0-BaseProject, which contains the basic Cocos2d setup and some integrated assets.

I’ve added directories for several stages of the development process containing the results you should achieve. These directories will make your life easier in case you get lost, or if you simply want to skip one part of the project.

Each folder contains the complete project and is independent from the rest. Inside each folder are two more folders:

The first is called Assets, and contains such things as the TexturePacker and PhysicsEditor save files, a directory holding the Xcode project, and a free game art pack created by Vicki Wenderlich.

The Assets folder is organized further into the subfolders background, containing the background graphics, and jungle, containing the foreground objects and animation.

The second folder is called MonkeyJump. It contains the Xcode project and the sources, which are contained in a second MonkeyJump folder which has the following subfolders:

  • libs: Cocos2d, Box2d, Cocos Denshion… all the Cocos2d stuff
  • GBox2D: my ObjectiveC++ Box2d wrapper
  • Resources: sounds and music

Creating Sprite Sheets


Time to start the real work, beginning with sprite sheets.

Open the 0-BaseProject folder and have a look at the Assets folder. I’ve already arranged the images for us. We’re going to add the sprites from the “background” folder into one sprite sheet, and the sprites from the “jungle” folder into as second.

The background sheet will use RGB565, a 16-bit image format that reduces the amount of memory used by 50%. Using RGB565 will also speed up rending. The foreground sheet, with most of the content, will use RGBA8888 for full quality. For more information on pixel formats with TexturePacker, check out this tutorial.

Creating the Background Sprite Sheet

Let’s start by creating the background sheet. Start TexturePacker, navigate to the O-BaseProject\Assets\background folder, and drag it into the right hand side of the TexturePacker window. You’ll see the jungle background image show up in the center of the window.



To set up the parameters for the texture, first choose the Data format, which is of course Cocos2d. Next choose the Texture format. We will use zlib compressed PVR format .pvr.ccz.

TexturePacker warns us that we should turn on pre-multiplied alpha. Let’s agree to that and click “Apply.”

Pre-multiply means that all color values get multiplied by their transparency value when saving the file. This speeds up graphics rendering in the game, since the multiplication step does not need to be performed at runtime.

The main advantage of pvr.ccz is that it can be loaded quite fast, and it usually consumes less memory than PNG. Note in the bottom-right corner of TexturePacker how the memory consumption is reduced from 8192kB to 4096kB.

The quality of the image will suffer a bit: we can see that the gradients are now not as smooth and have some artifacts called banding. We can compensate for this by setting Dithering to FloydSteinberg.

The following two images show a part of the jungle. The left one has no dithering, while on the right one, dithering has been enabled:


RGB565 image with banding artifacts


RGB565 image with dithering


Next, set the Data file to background-hd.plist in the Resources directory of the Xcode project. This will automatically set the Texture file to background-hd.pvr.ccz.

Don’t worry that the paths are displayed as absolute paths. TexturePacker creates a relative path to the document file as soon as it is saved. This means we can move our project around as long as we don’t change the relative position of the assets and resources to the saved .tps file.

The -hd extension is important, because TexturePacker can save retina display and reduced resolution images for older devices. To enable this, simply check the AutoSD option. This will create background-hd.plist and background-hd.pvr.ccz files for retina display, and background.plist and background.pvr.ccz for reduced resolution.

Max. width and Max. height appear in red, which means TexturePacker can’t layout the sprite within the texture’s dimensions. This is because padding is set to 2 by default.

Scroll down on the left pane and set both border padding and shape padding to 0. Now all numbers should appear in black.



Finally, let’s save our sheet as background.tps in the Assets folder by first clicking Save and then Publish. This creates four files in the Resources folder: background-hd.plist, background-hd.pvr.ccz, background.plist and background.pvr.ccz. (Open the Resources folder to make sure the files are there.)

Creating the Jungle Sprite Sheet

Now create a new sheet for the foreground by pressing the New button on the toolbar. Drag the complete jungle folder from the Assets folder into the empty right pane.

See how TexturePacker builds the complete directory structure on the right pane? (You can expand the tree view by pressing the arrow button to the left of the word “jungle”.)

Folders in Texture Packer

We’re using a feature called Smart Folders, where TexturePacker rescans the directory every time we add sprites to the folder. If you want to add a new asset, or rename or change an existing asset, just drop it into the folder on your file system, and when you reenter TexturePacker it will automatically update the sheet.


Note: If you need to update many sprite sheets at once, you can switch to Terminal and update all .tps files from the command line by calling TexturePacker *.tps.

You can even integrate TexturePacker with your Xcode build process. This has several advantages.

First, you no longer need to worry about sprite sheets – just add the sprites to your Assets folder, and you’re done.

Second, if you use version control, sprite sheets will hang around as binary blobs. This will grow your working copy size pretty fast, especially when using Git or Mercurial for version control. The easy way around this is to simply not add the sprite sheets to version control, and instead create them on the fly.

For more information on integrating TexturePacker with Xcode 4, check out this tutorial.

For the options, we’ll use a nearly identical setup as for the background sheet (see screenshot below). Just make sure to leave the image format at RGBA8888 for full quality.



Also be sure to leave the paddings set to the default of 2. This will reduce artifacts on the sprite borders. Sometimes OpenGL drags in pixels from neighboring sprites. Padding avoids this problem by adding transparent borders around the sprites.


Note: If you want to use sprites as tiles with seamless connections, you must use either select extrude or reduce border artifacts, which replaces the transparent borders with colored ones. If you do not do this, you might get transparent lines between the tiles.


Set jungle-hd.plist in the Resources folder of the project as the Data file, and jungle-hd.pvr.ccz in the same folder as the Texture file. Check the box next to AutoSD.

Finally, save the sheet as “jungle.tps” in the Assets folder and click Publish. This creates four files in the Resources folder: jungle-hd.plist, jungle-hd.pvr.ccz, jungle.plist, and jungle.pvr.ccz. Check and see if they are there.



Creating Physics Shapes Manually


Next we’ll set up the physics shapes with PhysicsEditor!

Launch PhysicsEditor and start with the basic setup. We need to set the Exporter to Box2d Generic (PLIST). For this I added a loader which you can use in your Cocos2d projects. If you are not satisfied with the formats supported by PhysicsEditor, you can simply create your own custom data exporter.

Set the PTM-Ratio to 170. This tells Box2d that 170 pixels are equal to 1 meter (39.37 inches), the internal measurement unit of Box2d. I chose 170 pixels because this is the monkey’s height, and he is going to be 1 meter tall in the simulation.

We’re going to create all the physics shapes for the high-res sprites only. This is okay, since we want the physics parameters to be identical on retina display and old displays.

Creating different shapes for different screen resolutions would create different masses for each object, resulting in different physics behavior – which we don’t want! The idea is to run the same simulation on all devices and only adjust the visuals.



Setting Up the Fixture

We’re now going to create our first shape by hand. Drag the jungle/floor/grassfront.png shape onto the left pane of PhysicsEditor. When you do this, the shape will also appear in the center pane, which is the main editor area.

Note the small blue circle with the cross inside: that is the anchor point of the shape. We’re going to leave the anchor point for this shape where it is, on the bottom right corner. Later on, I’ll show you how to change the anchor point.

First use the polygon tool from the top tool bar. As soon as you click on it, a small red triangle appears. You can drag this triangle with your mouse.

The handles allow you to change the triangle’s shape. Double-clicking somewhere near a line will add an additional vertex. Double-click the vertex to remove it.

You do not have to care about things like polygon orientation or convex or concave shapes. This is all handled by PhysicsEditor.

Now create a rectangular shape for the floor. It should cover the soil but not the grass, and look something like this:



Setting Up the Parameters

Since the floor is going to be a static shape, its parameters are going to be very basic.

Density affects the weight of a body/fixture. Since the floor will not move, the value of the density is of no importance. Restitution is the degree a colliding shape will rebound from another object. For the floor, we want to keep this at 0.

Friction is the only important value here, as it determines how much the sprites will slide on the floor. Set this to 0.7.

The next items to set up are the collision bits. PhysicsEditor lets you handle these parameters quite easily – that is, without doing hex math. First, give the bits useful names by setting up the names in the text fields associated with the bits:

  • floor – both the floor and the walls
  • monkey – what else?
  • good_objects – objects that don’t hurt the monkey
  • bad_objects – objectw that hurt the monkey

Ignore the other bits – we don’t need them.



Two objects can collide only when Object B’s bit category is of a type that has been selected as a mask for Object A, and vice-versa. We will tick the Category field for the floor bit since this shape is a floor, and then the Mask field for all the bits. This enables collision between all objects and the floor.

Save the project as “shapes.pes” inside the Assets folder.

A Little Magic: Creating Shapes with the Tracer


Creating shapes by hand isn’t always fun. So let’s use the magic wand tool and let PhysicsEditor do the work for us!

Drop the following objects onto the left pane: backpack, banana, bananabunch, canteen, hat, pineapple, and statue.



Select the backpack, and click the magic wand icon on the tool bar. This will open a new window, the tracer. The tracer shows the current shape with an overlay of the traced shape.



The most important setting is the Tolerance. This value tells the tracer how exactly the polygon should match the shape. It directly influences the number of vertices the polygon will have. For example, setting the Tolerance to 20 will result in a 5-vertex polygon that no longer fits the shape; setting it to 1 creates a perfectly-matching polygon with 39 vertices.


Not enough vertexes


Too many vertexes


Good trace


A Tolerance value of 5 gives us an acceptable match, with about 15 vertices (the exact amount sometimes varies with the starting point of the tracer). That’s fine! Click OK to get back to the main screen. If you want you can fine-tune the shape, but don’t be too finicky!

Now set the backpack’s parameters. Set the Density to 5.00, the Restitution to 0.10 (so that the backpack bounces a little bit) and the Friction to 0.5. You might want to play around with these parameters later to get a better feel for how they work.

In the collisions section, tick the Cat. box next to bad_objects, and enable collision with all other objects by making sure all the Mask boxes are ticked.

Also drag the anchor point (the blue circle with the cross inside) to the center of the backpack shape. Alternatively, you can set the anchor point to the exact center of the shape by setting the Relative anchor point values in the right sidebar to 0.5 and 0.5.



Now that you know how to create shapes, either by hand or using the tracer, go ahead and do the remaining ones yourself! Use the parameters indicted in the table below. And don’t forget to drag the anchor point for each shape to the position indicated in the images below.












































































ObjectToleranceDensityRestitutionFrictionCategory (Cat.)Mask
backpack55.00.10.5bad_objectsfloor, monkey, bad_objects, good_objects
canteen53.00.10.2bad_objectsfloor, monkey, bad_objects, good_objects
hat51.00.150.4bad_objectsfloor, monkey, bad_objects, good_objects
statue510.00.050.7bad_objectsfloor, monkey, bad_objects, good_objects
pineapple51.00.40.7bad_objectsfloor, monkey, bad_objects, good_objects
banana51.00.50.5good_objectsfloor, monkey, bad_objects, good_objects
bananabunch51.00.30.7good_objectsfloor, monkey, bad_objects, good_objects



Last But Not Least: the Monkey


There’s one shape we have left to create, and that’s because it’s the most complex. Our monkey consists of quite a few animation phases (fourteen total):



The first idea that comes to mind is to add a collision polygon for each animation frame to make a perfect match for each phase of the animation. But this would be a bad idea.

First of all, the frequent exchange of fixtures would consume a good deal of CPU power. But the bigger problem is that with each new shape, the mass of the monkey would change!

This is because Box2d calculates mass based on a polygon’s area and density. If you change the polygon, the monkey will gain or lose weight! And this will lead to the physics simulation behaving erratically.

The solution is to make only one shape for the monkey, which we will try to make as good a fit as possible. To begin, drag one of the monkey shapes onto PhysicsEditor. You can rename the shape by double-clicking its name.



Now click the “+” button to add the other animation phases for the monkey. The files will show up in the combo box and you can switch between them.

Start the tracer by clicking on the magic wand icon. What you see now is that the shape does not fit the monkey anymore. This is exactly what we want.



The tracer is now in animation tracing mode. You can switch between two frame modes: intersection and union. Intersection creates the polygon only from the parts that are covered by all sprites, whereas union uses the parts that are covered by any sprite. Choose intersection.

The slider allows you to browse through the animation phases and see how the shape fits the different phases.

We will take the shape the tracer gave us just as an estimate. This is because we must split up monkey’s body into several parts. Here is what we have to build:



Sometimes polygon shapes don’t slide smoothly over other polygons and stick to each other. This is why we’re building the monkey from circle shapes.

The other reason is that using circles results in faster collision detection. The math to check if a point is inside a circle is much simpler than that for testing for a point inside a polygon. So we’ll save CPU power. We’ll delete the tracer shape after the other parts are set up.

First build the head of the monkey. Use a circle shape and make it as big as the traced version. The head must be treated differently from the other body parts, since we want the monkey to get hurt when objects land on his head from above.

To distinguish the head from the other parts, set the Id to “head.” The head’s category is monkey, and it collides with good_objects, bad_objects and floor, so make sure these are selected as masks. Set the density to 2.0, the restitution to 0.1, and the friction to 0.5.

Next build the body of the monkey from two circles, one covering the torso and one the legs. Set the Id to “body.” The body’s category is monkey, and it collides with good_objects, bad_objects and floor. Set the body’s density to 2.0, its restitution to 0.1, and its friction to 0.5.

Cycle through the different animation phases by selecting the different images from the Filename combo box. Check if the circles fit all phases. It doesn’t have to be a perfect fit, and you can come back to PhysicsEditor any time you want to tweak the collision set.

Finally, delete the polygon created with the tracer.

During the game we need to check if there are objects to the left or right to trigger the push animation. To do this, place two sensors on the left and right sides of the monkey.

Sensors are fixtures that don’t interact with other bodies and simply report collisions. To make a fixture a sensor, set isSensor.

Set the Id to “push_left” for the left sensor and “push_right” for the right one. The category is monkey, and they collide with bad_objects only – we don’t want the monkey push the floor and the bananas away!


Make the monkey shape fit all animation phases

One last thing to do: save and click Publish! When asked for a location, store the file in the Resources folder of the project as shapes.plist.

That’s it for now in PhysicsEditor. Next we move to Xcode and start coding our game!

The Xcode Project: Overview


I created the starter project using the standard Cocos2d+Box2d template that comes with Cocos2d and removing all the demo stuff. I also added the sound resources and some classes which will make your life easier when working with Box2d inside Cocos2d.

One important thing to know about this project is that all files must have the .mm extension instead of .m. This is because Box2d is C++ based, so we must use Objective-C++ for development.

Now let’s discuss the starter project in more detail:

GBox2D

First let me give you some information about GBox2D. GBox2D is an Objective-C wrapper for Box2d that I developed for my upcoming game TurtleTrigger.

These are the main classes in Gbox2D:

  • GB2Engine: This class wraps the Box2d world simulation. It runs the simulation, updates all sprite positions and rotations and can iterate through all objects in the world. It is implemented as a singleton class to make access as easy as possible.
  • GB2Node: This class combines a CCNode and a B2Body. It’s the glue between the physics simulation and the graphics representation inside Cococs2d. It also contains selectors for simple management of the physics object and implements a proxy to access the inner node’s data.
  • GB2Sprite: This class is derived from GB2Node and specializes in using CCSprite as the inner object.
  • GB2DebugDrawLayer: This is a Cocos2d layer that wraps the debug drawing. It can be added to your project like a normal layer. When added it will draw the physics shape outlines. The nice thing about it is that it detects when running on a retina display target and scales the content accordingly.
  • GB2Contact: This structure will be passed as parameter to an object when a collision is detected. Both objects involved in the collision will be called for each single point of contact.
  • GB2WorldContactListener: This is a C++ class that reacts to collisions in the physics simulation.

If you’re curious, go ahead and scan through these classes to get an idea of what they do. Don’t worry if you don’t understand what they’re doing – you’ll learn how to use it in the next few sections.

Collision Detection with Gbox2D

GBox2D makes collision detection a piece of cake! This is because you do not need to create one huge switch-case statement or a series of if-else cascades to detect the various possible collision combinations.

Instead, GBox2D simply uses the names of the colliding classes and calls selectors with names derived from the class names! If this sounds too abstract, take a look at the following example:

Let’s assume you have a monkey that is an object of class Monkey, and a banana that is an object of class Banana. If both objects begin to collide, the following selectors will be called by GBox2D:


[banana beginCollisionWithMonkey:collisionA];
[monkey beginCollisionWithBanana:collisionB];


If the collision is released, because the objects do not touch anymore:


[banana endCollisionWithMonkey:collisionA];
[monkey endCollisionWithBanana:collisionB];


The collisionA and collisionB parameters contain collision information, e.g., which objects and which fixtures took part in the collision. We will use this information to see if the monkey was hit on his head or body.

AppDelegate

Things I changed from the AppDelegate contained in the original Box2d project are as follows:

First I set the default pixel format of the frame buffer to RGBA8. That means that the game gets the full 24-bit color depth. I disabled the depth buffer, since we don’t need it.


EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
pixelFormat:kEAGLColorFormatRGBA8
depthFormat:0
];


The next important thing to set is pre-multiplied alpha. This is because we use pre-multiplied PVR images created with TexturePacker. If we don’t set pre-multiplied alpha, our images will have dark borders.


[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];


Since we’re going to use the random generator to select objects to drop, we have to seed it. The best way to do this is using time(). If you forget to seed the random generator, you will still get random numbers – but they will be the same with every start of the game.


srand (time (NULL));


When the initialization is done, the GameLayer scene is started:


[[CCDirector sharedDirector] runWithScene: [GameLayer scene]];


GameLayer

The GameLayer is a simple class derived from CCLayer. In this state it consists of an empty init function…


-(id) init
{
if( (self=[super init]))
{
}
return self;
}


…and a static selector that wraps the CCLayer into a CCScene to hand over to the Director:


+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];

// 'layer' is an autorelease object.
GameLayer *layer = [GameLayer node];

// add layer as a child to scene
[scene addChild: layer];

// return the scene
return scene;
}


Audio Resources

I got the theme music, tafi-maradi-loop.caf, from http://incompetech.com/

Since I knew I wanted to loop the music, I made things easier on myself and chose a theme without a vocal track.

The sounds effects for the objects were obtained from http://soundbible.com (thanks to Mike Koenig). Some of them were created using cfxr.

All sounds and the music files were converted to caf format. See Ray’s Audio 101 tutorial for more information.

If you compile and run the project, you will simply see a black screen. So let’s add some content to that screen now!

Basic Setup in Xcode


The goals for this section of the tutorial are to set up the basic game layers and backgrounds, and to set up the physics engine.

Before we dive into the code, there’s one more thing to do: add the resources we created in PhysicsEditor. Remember these?

  • background.plist
  • background.pvr.ccz
  • background-hd.plist
  • background-hd.pvr.ccz
  • jungle.plist
  • jungle.pvr.ccz
  • jungle-hd.plist
  • jungle-hd.pvr.ccz
  • shapes.plist

Add the above files to the Resources folder in your Xcode project by Control-clicking on the Resources folder inside Xcode, selecting Add Files To “MonekyJump” and then selecting the files listed above from the project Resourcess folder.

Now for the code. First, we need to create a Floor class to represent the floor for the game. Add Floor.h and Floor.mm files to your project by creating a new file with the iOS\Cocoa Touch\Objective-C class template. Name the class Floor, and make it a subclass of GB2Sprite. And don’t forget to change the extension for Floor.m to .mm once it has been created.

Floor.h simply contains this:


#pragma once

#import "cocos2d.h"
#import "GB2Sprite.h"

@interface Floor : GB2Sprite
{
}

+(Floor*) floorSprite;

@end


And Floor.mm this:


#import "Floor.h"

@implementation Floor

+(Floor*) floorSprite
{
return [[[self alloc] initWithStaticBody:@"grassfront" spriteFrameName:@"floor/grassfront.png"] autorelease];
}

@end


The only remarkable line of code here is the call to the initWithStaticBody selector. This makes our object a static object – one that isn’t moved by the physics engine. It initializes the body’s shape using a shape from the shapes.plist file with the name “grassfront.”

It also uses a sprite image with the name floor/grassfront.png that is taken from jungle.plist.

Why did we derive this class from GB2Sprite instead of simply using a GB2Sprite directly? The answer is GBox2D’s collision handling, which uses the name of the class to call appropriate selectors on the colliding objects. Since we want to know when something collides with the floor, the class name for the floor object must be distinguishable from other GB2Sprite objects.

The next thing to do is update the GameLayer. Add some instance variables to hold the required objects in GameLayer.h:


@interface GameLayer : CCLayer
{
CCSprite *background;                   // weak reference
CCSprite *floorBackground;              // weak reference
CCSpriteBatchNode* objectLayer;         // weak reference
}


We will store the objects as weak references – that is, without increasing the retain count for each object.

You do not need to worry about the CCSprites being deleted. They will be added as children of the CCLayer and thus have a retain count of at least 1. This is done because otherwise we will be caught in a retain cycle and not able to free the memory allocated by these objects.

Now fill GameLayer.mm‘s init selector with content. First, load the sprite sheets:


[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"jungle.plist"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"background.plist"];


Next, load the physics shapes into the GB2ShapeCache:


[[GB2ShapeCache sharedShapeCache] addShapesWithFile:@"shapes.plist"];


Then, set up the layers. We’ll divide the game into the following layers:

  • Background layer: The jungle image
  • Floor background: A single sprite with the tall grass
  • Object layer: Contains all the items and the monkey
  • Debug draw layer Activated as needed
  • Hud layer Has the score and live energy indicators (to be added later)



Add the code to create the basic background and floor background layers to init:


// Setup background layer
background = [CCSprite spriteWithSpriteFrameName:@"jungle.png"];
[self addChild:background z:0];
background.anchorPoint = ccp(0,0);
background.position = ccp(0,0);

// Setup floor background
floorBackground = [CCSprite spriteWithSpriteFrameName:@"floor/grassbehind.png"];
[self addChild:floorBackground z:1];
floorBackground.anchorPoint = ccp(0,0);
floorBackground.position = ccp(0,0);


Then, add the object layer. This will be a sprite batch node to speed up rendering of the objects:


objectLayer = [CCSpriteBatchNode batchNodeWithFile:@"jungle.pvr.ccz" capacity:150];
[self addChild:objectLayer z:10];


And finally, the debug draw layer:


// add the debug draw layer, uncomment this if something strange happens ;)
[self addChild:[[GB2DebugDrawLayer alloc] init] z:30];


If you want to disable the debug drawing, simply comment out the second line. If enabled, the physics shapes will be drawn over the sprites, allowing you to see where collisions happen and if all shapes are properly aligned.

Next, add the floor object as the child of the object layer. Include Floor.h at the top of GameLayer.mm:


#import "Floor.h"


Then add the floor object at the end of init:


[objectLayer addChild:[[Floor floorSprite] ccNode] z:20];


There isn’t anything more we have to do to add the objects to the physics world – everything else is covered inside Gbox2D!

Compile and run the project in the iPhone simulator. (By the way, the project in its current state is available in the folder called 2-BasicLayerSetup.) You should see something similar to this:



Nice – now let’s add some action to the game!

Dropping Objects


We have two related goals for this section of the tutorial: make our objects drop from the sky and add our sound effects.

Our base class for all the dropping objects will be called Object. It will handle the sound and some basic collision detection. We will derive other sub-classes later on in the tutorial from the Object class.

First, create a new file with the iOS\Cocoa Touch\Objective-C class template. Name the class Object, and make it a subclass of GB2Sprite. (And remember to change the extension for Object.m to .mm)

Object is a simple class, derived from GB2Sprite. This means that it comes with physics and graphical capabilities built in.

To make our lives easier, I’ve named the sound files in the same way as the physics sprites and the images from the sprite sheet. This allows us to simply use the object’s name to create the right shape and sound when needed. You’re welcome!

In order for this to work, we need a property named objName – objName is passed into the initWithObject selector and stored as part of the class.

RandomObject is a factory method that creates a random object and hands over the right object name upon creation.

Paste this code into Object.h:


#pragma once

#import "cocos2d.h"
#import "GB2Sprite.h"

@interface Object : GB2Sprite
{
NSString *objName; // type of the object
}

@property (retain, nonatomic) NSString *objName;

-(id) initWithObject:(NSString*)objName;
+(Object*) randomObject;

@end


Let’s now go to Object.mm. Start with some needed imports and with synthesizing the objName property.


#import "Object.h"
#import "GB2Contact.h"
#import "SimpleAudioEngine.h"
#import "GMath.h"

@implementation Object

@synthesize objName;


GMath.h contains some helper functions – for example, gFloatRand, a ranged floating point random number generation.

Next, add the init selector and instantiate the physics object. You can use the object’s name as it is to instantiate the physics shape. For the sprite frame name, you’ll need to add the folder’s name (which is object) and the .png extension. Store the objName in the property – we’ll need it during collision detection to play the sound effect.


-(id) initWithObject:(NSString*)theObjName
{
self = [super initWithDynamicBody:theObjName
spriteFrameName:[NSString stringWithFormat:@"objects/%@.png", theObjName]];
if(self)
{
self.objName = theObjName;
}
return self;
}


In the dealloc selector, simply release the objName property and call super dealloc:


-(void) dealloc
{
[objName release];
[super dealloc];
}


The next thing to add is our static factory method, which will simply create a random object. I decided to use a simple switch-case statement for this. The reason is that we’ll need to create special classes for banana and banana bunch later on. These two objects get only one case entry, while the other objects get three each, so that there’s a higher probability they appear more often.

Switch case constructs are quite efficient (usually implemented by the compiler using a jump table). You might save some CPU cycles by using an array with the names instead, but since the routine will be called once in a second, our way is fine.


+(Object*) randomObject
{
NSString *objName;
switch(rand() % 18)
{
case 0:
objName = @"banana";
break;

case 1:
objName = @"bananabunch";
break;

case 2: case 3: case 5:
objName = @"backpack";
break;

case 6: case 7: case 8:
objName = @"canteen";
break;

case 9: case 10: case 11:
objName = @"hat";
break;

case 12: case 13: case 14:
objName = @"statue";
break;

default:
objName = @"pineapple";
break;
}
return [[[self alloc] initWithObject:objName] autorelease];
}


Finally, add the closing end to the file:


@end


Now switch to GameLayer.h and add a forward declaration for the object class, directly after the #import statement:


#import "cocos2d.h"
@class Object;


Add these new members to the GameLayer class:


ccTime nextDrop;    // Will keep the time until the next drop.
ccTime dropDelay;     // The delay between two drops.
Object *nextObject;   // Contains a reference to the next item to drop.


Switch to GameLayer.mm and add an import of Object.h to the imports at the start of the file. Also import GMath.h:


#import "Object.h"
#import "GMath.h"


Initialize the new variables at the end of the init selector, and schedule an update selector with every frame update:


nextDrop = 3.0f;  // drop first object after 3s
dropDelay = 2.0f; // drop next object after 1s                

[self scheduleUpdate];


The last line will call a selector called “update” for every frame. The parameter to this selector is the time elapsed since the selector was last called. Add the update method right after init:


-(void) update: (ccTime) dt
{
// 1 - drop next item
nextDrop -= dt;
if(nextDrop <= 0)
{
// 2 - do we have the next object?
if(nextObject)
{
// 3 - set the object as active, making it drop
[nextObject setActive:YES];

// 4 - set next drop time
nextDrop = dropDelay;
// reduce delay to the drop after this
// this will increase game difficulty
dropDelay *= 0.98f;           

}

// 5 - create new random object
nextObject = [Object randomObject];
// but keep it disabled
[nextObject setActive:NO];

// 6 - set random position
float xPos = gFloatRand(40,440);
float yPos = 400;
[nextObject setPhysicsPosition:b2Vec2FromCC(xPos, yPos)];

// 7 - add it to our object layer
[objectLayer addChild:[nextObject ccNode]];
}
}


Let’s go through the above code section by section.

  1. This section simply reduces the time interval since update was last called from nextDrop. If nextDrop falls below 0, it’s time to create a new item to drop.
  2. If the nextDrop timer runs out, this section checks if there is already an object stored in nextObject.
  3. If so, it’s set to to active in here. Setting the object to active gives the physics engine control over the object.
  4. This section sets the time until the next drop to the current drop delay, and reduces the drop delay by 2%, making the game a bit more difficult with each dropped item.
  5. This section creates a new object to drop using our factory method in Object – randomObject – and sets the object to inactive, which keeps the object from dropping and participating in the physics simulation.
  6. This section gives the object a random position. The screen is 480pt wide (Cocos2d uses points as the base unit, with 1 pt equivalent to 1 pixel on “old” devices and 2 pixels on retina display devices). The code ensures that the object’s position is somewhere between 40 and 440 points. The section also sets the y-coordinate to 400 for the starting position so that the object will start offscreen from the top of the screen. The b2Vec2FromCC method is used to create a box2db2Vec2 from the point coordinates. B2Vec2FromCC transforms Cocos2d’s points to Box2d’s meters-based values.
  7. Finally, this section adds the object to the object layer.

Compile and run! You should see something similar to the following but of course, with different items. The items look a bit blurry since debug drawing is still enabled:



Disable the debug draw layer as follows by commenting out the relevant line in GameLayer.mm:


//        [self addChild:[[GB2DebugDrawLayer alloc] init] z:30];


Now your game should look much nicer:



Notice how the items can tumble out-of-screen to the left and right? The goal of the game is to let the items pile up, so we need to add a wall on each side of the screen.

To do this, simply create two new GB2Node objects. They will be out of the screen to the left and right.

Since GB2Nodes add themselves to the current physics simulation, you don’t need to add them manually. They are not represented graphically, so creating them will suffice.

Add these lines to the init in GameLayer.mm, right after the floor layer:


GB2Node *leftWall = [[GB2Node alloc] initWithStaticBody:nil node:nil];
[leftWall addEdgeFrom:b2Vec2FromCC(0, 0) to:b2Vec2FromCC(0, 10000)];

GB2Node *rightWall = [[GB2Node alloc] initWithStaticBody:nil node:nil];
[rightWall addEdgeFrom:b2Vec2FromCC(480, 0) to:b2Vec2FromCC(480, 10000)];


Compile and run. See how the objects are now kept inside the screen by our walls?



This looks nice, but there is still something missing. I think the objects should make some noise when colliding with each other. Don’t you agree?

I don’t want the objects to make sounds all the time, just when they hit each other at a decent speed. So we’ll check the object’s velocity, and play a sound only when it collides at a fast enough speed.

Add this code to Object.mm:


-(void) beginContactWithObject:(GB2Contact*)contact
{
b2Vec2 velocity = [self linearVelocity];

// play the sound only when the impact is high
if(velocity.LengthSquared() > 3.0)
{
// play the item hit sound
// pan it depending on the position of the collision
// add some randomness to the pitch
[[SimpleAudioEngine sharedEngine] playEffect:[NSString stringWithFormat:@"%@.caf", objName]
pitch:gFloatRand(0.8,1.2)
pan:(self.ccNode.position.x-240.0f) / 240.0f
gain:1.0 ];   

}
}


The above method must be named beginContactWithObject so that it will be automatically called by GBox2D each time two objects collide.

The linearVelocity method gives us the velocity of the object. Calling Length or LengthSquared on the object delivers the velocity’s value. I prefer using LengthSquared when comparing with a constant value, since it doesn’t require calculating the square root of the value.

We’ll play the sound with a call to SimpleAudioEngine’s playEffect method. The first parameter is the name of the audio file.

Remember that to make our lives easier I gave the sound effects the same name as the objects and sprites. So you can use the objName we stored earlier to get the right sound file. Use NSString to append .caf to the name.

Add some variation to the pitch by using gFloatRand with 0.8 and 1.2. This will play the sound with some pitch variation. It would be boring if every object made the same sound all the time.

The last trick to apply is to pan the sound’s source to the position of the object. Pan allows values between -1.0 and 1.0. The object’s x position (in points) will be somewhere between 0 and 480, so subtracting 240 and dividing by 240 will deliver that range.

If you want objects to make a sound when they hit the floor without rewriting a lot of the code, add the following method which forwards the object-floor collision to the object-object collision to Object.mm:


-(void) beginContactWithFloor:(GB2Contact*)contact
{
[self beginContactWithObject:contact];
}


Compile, run and see how the objects drop and make a sound upon collision.

Ah, but there is one more thing I don’t like about our game right now. The first item drops and then pauses in mid-air while the sound engine is initialized.

This won’t be a problem once we add the theme music, since the music will initialize the sound engine right away. But if you want to fix this now, first add an import statement to the top of GameLayer.mm:


#import "SimpleAudioEngine.h"


Then, add a call to SimpleAudioEngine’s shared object inside GameLayer’s init selector:


[SimpleAudioEngine sharedEngine];


The above implementation plays the same basic sound (with pitch variations) for all falling object collisions. If you’re ambitious, you could play different sounds depending upon the types of objects colliding. That is, play one sound when a canteen hits a canteen, and another when a banana hits a canteen…

Another way to improve this code would be to vary the gain of the effect with the speed of the collision.

Where to Go From Here?


If you don’t have it already, here is all of the source code for this tutorial series.

You’ve now reached the end of Part One of the MonkeyJump tutorial! The project in its current form is available in the source code zip in the folder called 3-DroppingObjects.

Stay tuned for Part Two, where we’ll add our hero (the monkey), make him move and interact with objects – even make him teleport! Plus injury and death, life-giving bananas, a drop warning light… there’s lots of exciting stuff ahead.

Before we get there, let me know if you have any questions or comments about what we’ve done so far. I’ll be following the discussions in the forum below.

This is a post by special contributor Andreas Loew, the creator of TexturePacker and Physics Editor.

How To Build a Monkey Jump Game Using Cocos2D, PhysicsEditor & TexturePacker Part 1 is a post from: Ray Wenderlich

Debugging with GDB: Print-Object and UIView recursiveDescription

Debugging with GDB: Print-Object and UIView recursiveDescription:
In the post Debugging with GDB: Introduction to Commands, Print and Print-Object I covered the basics of the command line inteface in GDB. In this post I’ll show you a trick to print out the entire view hierarchy for UIView objects.

In Objective-C, all objects (derived from NSObject) have a description method, which returns an NSString describing the object. When using GDB, you can print the description using print-object, for example, let’s use the interface definition below to look at a few descriptions:




@interface SandboxViewController : UIViewController <UITextFieldDelegate>
{
UITextField  *username;
UIButton     *testButton;
UILabel      *label;
UIView       *view;
}


When stopped on a breakpoint in the SandboxViewController object, GDB can display information on each object:



Note, po is equivalent to print-object.

Print-Object and recursiveDescription

When working with UIView objects, there is an additional method for obtaining information, recursiveDescription. When using print-object and calling this method you can see the entire view hierarchy for the object.

With the SandboxViewController object defined above, in the loadView method I created a UIView as follows:


[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];


Within GDB, when on a breakpoint within the SandboxViewController object, I can now view the entire view hierarchy as follows:



The same idea works for a UIView that is not associated with a view controller. Using the view defined below, and the label added as a subview:


// Create UIView
view = [[UIView alloc] initWithFrame: CGRectMake(10, 10, 300, 50)];
[[self view] addSubview:view];

// Add label to UIView
UILabel *tmplabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 280, 80)];   
[tmplabel setTextColor:[UIColor whiteColor]];
[tmplabel setTextAlignment:UITextAlignmentLeft];
[tmplabel setText: @"Enter your password:"];
[view addSubview:tmplabel];


Here is the recursive description:



2012年1月17日星期二

How to Make a Game Like Jetpack Joyride Using LevelHelper & SpriteHelper – Part 1

How to Make a Game Like Jetpack Joyride Using LevelHelper & SpriteHelper – Part 1:

This is a post by special contributor Bogdan Vladu, an iOS application developer and aspiring game developer living in Bucharest, Romania.


Learn how to create a game like Jetpack Joyride with LevelHelper and SpriteHelper!

Learn how to create a game like Jetpack Joyride with LevelHelper and SpriteHelper!


In this tutorial series, we will create a game similar to Jetpack Joyride using Cocos2D and Box2D. If you haven’t played Jetpack Joyride yet, you should check it out – it’s an incredibly polished and fun game, and best of all it’s free! :]


You could make this game with Cocos2D alone, but it would take a lot of time. To make things simpler, we’re going to use two tools written by yours truly – LevelHelper and SpriteHelper.


If you aren’t familiar with these tools, here’s a quick synopsis:



  • LevelHelper is a tool that makes creating levels much easier. You literally drag and drop sprites onto the scene!

  • SpriteHelper is a tool that creates the sprite sheets and physics shapes for your games quickly and easily.


This is going to be a complex game, and we have a lot to do, so this series will be spread over four parts. In this first part, we’ll first spend some time setting up LevelHelper. Then we’ll create a basic level with a continuous scrolling parallax, and learn how to use SpriteHelper to add and modify our art.


By the end of this series, not only will you have earned valuable experience with these tools – you will have an exciting, sophisticated game to play!


This tutorial assumes you have some basic familiarity with Cocos2D and Box2D. If you are new to either of these game frameworks, you should check out our Cocos2D and Box2D tutorials first.



Getting Started


To get started, you just need to download several things:



Note: LevelHelper supports the latest version of Box2D, but Cocos2D comes shipped with a slightly older version of Cocos2D. Using the LevelHelper template makes things easier for you because it pre-integrates the latest version of Box2D. If you want to use the normal Cocos2D template and integrate the latest version of Box2D yourself, check out the instructions in the official LevelHelper Cocos2D/Box2D Documentation.


Installing the LevelHelper Template


First, make sure you have the Cocos2D 1.X templates installed (i.e. not Cocos2D 2.X). If you have the Cocos2D 2.X templates installed, just download the 1.X templates from the Cocos2D download page and re-install the templates. You can always re-install the Cocos2D 2.X templates again when you need them later.


Next, unpack Cocos2dBox2dXCode4Template.zip. You will have the following folder structure:



Click once on your desktop in an empty space to make Finder the active application (and hence show its menu bar). From the menu bar, navigate to Go:



While still on the Go menu, press and hold the Option (or Alt) key, and the Library folder will now be visible. Pretty cool trick, eh? Click on it to continue.



You should now be looking at your computer’s Library folder. The full path to Library is /YOUR_HD/Users/YOUR_USER_NAME/Library.


Now navigate to Developer/XCode/Templates/Cocos2D. Copy both of the folders from the unpacked Cocos2dBox2dXcode4Template.zip file into this folder.



The resulting folder structure should look like this:



w00t you’ve installed the template! Now let’s try it out.


Creating Our Xcode Project


Open Xcode and choose File\New\New Project from the main menu.



Select the iOS\cocos2d\LevelHelper_With_Cocos2d_And_Box2d template, and click Next.



In the next dialog, name your product “RocketMouse” (no spaces), and click Next again.



Compile and run the project, and you’ll see a sample level that was made with LevelHelper:


LevelHelper Sample Level


Nice – soon you will see how easy it is to create these levels yourself! :]


Cleaning Up What We Don’t Need


We could extend the template code from here, but to give you the best understanding of how everything works we’re going to start from scratch.


So let’s clean up everything we don’t need from the template code. There are two steps: cleaning up the resources, and cleaning up the code.


Keep reading to clean this up yourself, but if you’re feeling particularly lazy, you can download the cleaned up project and just skim over these steps :P


1) Cleaning up the resources


Inside Xcode, navigate to the Resources folder and select all files inside the Images and Levels folders.



Now Control-Click (or right click) and choose Delete.



In the pop-up window, choose Delete.



2) Cleaning up the code


Navigate and click on HelloWorldScene.h and delete the line b2MouseJoint* mouseJoint;



Now navigate and click on HelloWorldScene.mm. In the init method, delete the commented code and the notifications code, none of which we need.



Delete the unneeded methods used for the removed notifications.



Delete the content of all touch methods (DO NOT REMOVE THE METHODS THEMSELVES).





Delete the acceleromenter method:



Finally, delete the mouse joint release code from dealloc method:



Note: The project will compile at this point, but if try to run it it will crash with an assertion failure, as it has no level to load. Don’t worry, we will create one soon! :]


Examining the Cleaned Up Code


If you look through HelloWorldScene.m, you’ll see that there is very little code left. It creates a Box2D world, sets up Box2D debug drawing, and in the update loop runs the Box2D simulation and updates sprites to follow their associated Box2D body.


It also contains some LevelHelper setup code in init:



lh = [[LevelHelperLoader alloc] initWithContentOfFile:@"bezierTile"];         

//creating the objects
[lh addObjectsToWorld:world cocos2dLayer:self];

if([lh hasPhysicBoundaries])
[lh createPhysicBoundaries:world];

if(![lh isGravityZero])
[lh createGravity:world];


The first line initializes LevelHelper with an initial level. It then has a few lines to allow LevelHelper to add objects to the Box2D world and create physics boundaries and gravity based on the level settings.


Take some time to look through HelloWorldScene.mm and make sure you understand the basic idea of what’s going on so far. We’ll build up from here! :]


Preparing for LevelHelper


Let’s create two folders in the Resource folder of our Xcode project. While we don’t really need to do this, keeping our project organized will make our work easier!


In Finder, navigate to your Xcode project, open its Resources folder, and create two subfolders named “Images” and “Levels”. Important: Create these in Finder, not Xcode!


You should end up with something like this:



Creating a LevelHelper Project


Now that the project setup is complete, we can finally start creating our level with LevelHelper!


Beginning with version 1.4, LevelHelper will keep things organized in projects. This means level files are part of the project rather than individual files, as they used to be.


So let’s create a new project with LevelHelper. Open it up and go to File\New Project:



A new sheet window will appear. In the Project Name field, enter “RocketMouse,” the name of our project. Leave the Screen Size as the default, “iPhone Landscape (480×320).”


Note: When you want to create a game for all models of iPhone and iPad, you generally want to choose iPhone with Landscape or Portrait orientation. LevelHelper will automatically use SD on iPhone2G/3G/3GS and HD on iPhone4/4S and iPad1/iPad2.


If you want to create a game only for iPad, use the iPad template and inside SpriteHelper, unselect “Save SD” when creating the sprite sheets.


For iPad there is also an option to not stretch graphics. That won’t work for this tutorial, because we will be using continuous scrolling parallaxes.


Under “SpriteHelper scenes and image files directory,” choose the Images folder you just created inside the Resource folder, and click Open.



Under “Path to source code,” select the RocketMouse folder from inside the RocketMouse project folder. This is the folder that contains the LevelHelper folder. Click Open.



This setting tells LevelHelper where to go to automatically generate code, when needed.


Under “Engine” select “Cocos2d With Box2d.” Here you are selecting what code you want LevelHelper to automatically generate for you. For this tutorial, we will use Cocos2d With Box2d, but as you can see LevelHelper supports several other engines/configurations as well!


Make sure that the “Auto generate code when needed” option is selected. This tells LevelHelper to generate the code when there’s been an update to the code, or after you’ve added new tags to your project.



Under “LevelHelper scenes directory,” choose the Levels folder you just created inside the Resource folder, and click Open.



The final Project setting window should look something like this:



Note: Next to every major feature inside LevelHelper there is a “?” button. Click it to view a movie explaining that feature.


When you’re done, click the Create New Project button. A new window will appear asking you to save the project to a file.


Save the new file in the same folder as the Xcode project (RocketMouse.xcodeproj).



Now the LevelHelper window should look something like this:



But we have no image, no nothing! Time to start adding our art.


Adding Art to Our LevelHelper Project


To add our art, we need to use SpriteHelper, so go ahead and open it up.


Now navigate to where you saved the art pack for this tutorial. Select the particular files shown in the screenshot below (not all of them, just the ones shown), and drag them inside SpriteHelper.



In the Sheet Editor window on the right, uncheck the Crop option. Crop removes transparent space on sprites, but for some of our animations the sprites use transparency for placement so we don’t want the transparency modified.


For animations, it’s almost always best to uncheck Crop (to be renamed “Trim” in the next update).


Now click the Pack Sprites button at the bottom of the Sheet Editor window.



The resulting scene should look similar to this (sprites may be packed differently):



Save the scene inside the Images folder inside the Resource folder. Go to File\Save As.



In the Save dialogue window, name the scene “objects” and click Save.



If you look inside the LevelHelper window now, you’ll see that the art has automatically been added for you.


LevelHelper keeps track of all the changes inside the Levels and Images folders, just as we told it to when we created the project. Every time you add, remove or modify a file inside those folders, LevelHelper will automatically update its content.



Note: If you do not see the art in LevelHelper, click the bar above project settings and make sure the path to the Images folder is correct, and that the path does not contain any spaces.


Creating a Basic Level


Let’s start by creating a level with a scrolling floor and wallpaper background.


We first want to create a continuous scrolling parallax that will move from right to left. To do this, let’s decide how big our parallax will be. You can make it as big as you want.


Let’s make our game world the size of 8 screen sizes. Click the Game World Size button.



In the Width field, enter 3840. This is 8 multiplied by 480 (the width of the iPhone screen).



Now let’s create the background. Drag “bg” sprite into the level, and place it right at the beginning of the first screen. The first screen should be on the left side, and is demarcated by a red border.



Now we’re going to duplicate the sprite so that it covers all of our screens. With the background sprite selected, set the clone direction as in the image below so that you clone in the right direction.


Then click the green + sign. This is the clone button. (Alternatively, you could press Command+D). Continue pressing this button until the background sprite covers all sections of all eight screens. Do not go any further.


Note: You can scroll the level in LevelHelper by holding control as you drag the level, and you can zoom in and out by holding the option key as you scroll the mouse wheel.



It should look like this:



Let’s add these images to a continuous scrolling parallax. Navigate to the Parallax tab (the one that says “P”) and press the New Parallax button.



With the parallax selected, check the Continuous Scrolling option. Now select all the background sprites in the level, and click the Add Selected Scene Sprite(s) button in the parallax section.



There are still some adjustments to make to our continuous scrolling parallax. First, set the Speed preliminarily to 2.5 (we will change this later to match the movement speed of the mouse). Make sure that the Direction is set to Right to Left.


Now select all sprites in the parallax list and set the Movement Ratio to “1” and “0.” This ratio and the speed determine the rate at which the sprites will move through the parallax.



In this case, the sprites will move at the rate of 1*2.5 (ratio*speed). If we want other sprites to move at a different rate, we can modify the ratio accordingly (e.g. 0.4*2.5).


If you run Scene Tester right now (download and install it if you need to), it will move the continuous parallax, continuously!



Let’s save this level and run it in our Xcode project. Inside LevelHelper, go to File\Save Level As.



In dialogue box, enter “level01″ and click Save.



By saving the level, we caused LevelHelper to update the Levels section. Navigate to the Sprites section and then go the Levels to see the level file. By double clicking on a level, you can open that level inside LevelHelper.



Now let’s move back to Xcode. Open your RocketMouse Xcode project if it’s not already. Right click or Control-click on the Resources folder inside Xcode, and select Add Files To “RocketMouse.”



A new window will appear. Navigate to the Resources folder on your hard drive and select both the Images and the Levels folders. Then press the Add button to copy them to the Resources folder in Xcode.



Your new Resources folder inside Xcode should look like this:



Now navigate to HelloWorldScene.mm in Xcode. Select it and look for where in the code the level is loaded.



Replace the level name in this section of code with your level name, in this case “level01.” The new line of code should read:



lh = [[LevelHelperLoader alloc] initWithContentOfFile:@"level01"];


Now compile and run.



That’s all it takes to run your level – pretty cool eh? However, when running the level you will notice some artifacts:



This is caused by pixel perfect sprites (no overlap between them) moving next to each other constantly. How to fix this? Cocos2d to the rescue.


Navigate to libs/cocos2d/ccConfig.h:



In ccConfig.h, look for these three lines of code near the top of the file, around line 54:



#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0
#endif


Change the 0 to 1:



#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 1
#endif


Now when you run the project, you shouldn’t see any artifacts.


You can download the project as it stands up to this point here.


Creating the Full Level


Let’s go back to LevelHelper and add the remaining art so that we have a final level to play with.


Drag the small bookshelf onto the main screen. Drag it around until you are satisfied with its placement relative to the background sprite.


With the bookshelf sprite selected in the level, click the Clone And Align button in order to make multiple clones of this sprite.



Set the number of clones to 7, and set offset X to 500 and offset Y to 0.


You should see a series of blue or purple outlines indicating how the sprites will be set in the level. Click the Make Clones button when you are satisfied.


Note: Right clicking on any stepper button will reset the associated field to the default value.



Now let’s repeat the process to add the rest of the art.


Add in the big bookshelf, the cat, the dog and the window sprites and place them according to your preferences.


I’ve opted to put the dog under each window, because dogs like to look out the window. I’ve placed the cat next to each mouse hole, for obvious reasons. And I’ve placed the bookshelves randomly in the level.


My final level looks like this:



If you enable the Show Polygon Shapes option inside LevelHelper, you’ll see that all sprites have physic shapes on them.



Previously (in LevelHelper 1.3), we had to disable this behavior for each sprite inside LevelHelper. Now we can make it so that what we update in the SpriteHelper scene will also be updated in the level file.


If for our sprites we have “Handled by SpriteHelper” selected each time we do a change in the corresponding SpriteHelper document, the change will be immediately visible in the level. We no longer need to reopen that level or modify the previously added sprites in the level.



Fortunately “Handled By SpriteHelper” is the default setting, so we shouldn’t need to do anything to enable it. Let’s open up the SpriteHelper document and modify the settings on the sprites.


We can do this by opening SpriteHelper and then opening that document, but there’s an easier way:


I will do this process the long way so that you learn everything. In the list of sprites on the left side of the LevelHelper interface, select a sprite and Control-Click (or right click) on it. Now select Show SpriteHelper Scene.



This will take you to the SpriteHelper Scenes section and select the corresponding scene file for you. (this is very helpful, because sometimes it’s hard to remember from which scene a sprite came.)


Now Control-Click (or right click) on the scene and select “Open In SpriteHelper.”



This will open the needed scene in SpriteHelper, where we can select the sprite we want to modify and select “No Physics” under the Physics tab.



Make sure to save the scene when you’re done.


Now if you go back to LevelHelper, you’ll see that the physics shapes have disappeared. Save the level as new one by pressing Command-Shift-S. Give it the name “level02.”


If you run Scene Tester now (press “Test Level” button), you’ll see that only the background sprite will move.


Let’s add the other sprites to the parallax. To do this, first select all sprites except the background sprites that have already been added to the parallax.



Now go to the Parallax tab, select your parallax and add the selected sprites.


Select the sprites from the list of sprites in the parallax, and set the Movement Ratio to 1 and 0.



If you run Scene Tester now, all sprites should move with the same speed continuously.


Notice that the shape objects for the dog and cat sprites are basic quads.



Let’s make the shapes trace the dog and cat, so that they move with the correct physic behavior.


To do this, open the SpriteHelper scene as we did in the previous step by selecting the dog sprite and navigating to the correct scene file.


Inside SpriteHelper, select the dog sprite, navigate to the Physics section and click the Create Shape button.



Now click and trace the shape around the dog. Click Finish Shape when you are done.


Notes:



In SpriteHelper you can pan the view with 2 finger on the trackpad and move, or by holding Option key and drag with the mouse.

To zoom in or out you can use the popular pinch gesture on the trackpad or the mouse wheel.



Note: You can change a shape by clicking the “Edit Shape” button and then dragging the points as needed. You can add new points by clicking on the shape line. You can remove points by holding the Control key and clicking on a point.


Repeat the process for the cat. When you’re done, make sure to save the scene.


Now let’s try it out! Back in Xcode, control-click on your Resources\Levels folder, select Add Files to RocketMouse, and find your new level02.plhs level. Then modify the line that loads the level in HelloWorldScene.mm to level02:



lh = [[LevelHelperLoader alloc] initWithContentOfFile:@"level02"];


Compile and run, and now your level is looking a lot more interesting!


Basic scrolling level made with LevelHelper


Where to Go From Here?


So now we have our basic level! But most significantly – we’ve learned a great deal about navigating within and between LevelHelper and SpriteHelper, and adding and modifying that all-important art.


You can download the entire project up to this point here.


In Part Two, we’ll learn how to add and work with animations and sensors. We’ll also create our player, and begin working with tags – the first step in implementing collisions between sprites. In other words, the action begins!


Things will get even more interesting in the third and fourth parts. Besides fully implementing collisions, we’ll animate takeoffs and landings, learn how to kill the player and restart the game, create and display a scoring system, and add plenty of other cool features.


In other words, you definitely want to stay tuned! Getting through the basics is always challenging, so if you’ve made it this far, congratulations. In the meantime, I look forward to reading and responding to your questions, comments and suggestions in the LevelHelper forum and in the forum below.




This is a post by special contributor Bogdan Vladu, an iOS application developer and aspiring game developer living in Bucharest, Romania.


How to Make a Game Like Jetpack Joyride Using LevelHelper & SpriteHelper – Part 1 is a post from: Ray Wenderlich