2012年10月28日星期日

Creating an iPad flip-clock with Core Animation

Creating an iPad flip-clock with Core Animation:
flipclock_oneAs part of the sliding puzzle game I’m developing for the iPhone and iPad (well, I can’t survive on the profits from BattleFingers forever), I looked for a way to represent a numeric score and time display in an interesting way. One of the nicer visual effects you could use for this is the “flip-card clock” style, where each number consists of a top and bottom part, and the top part flips down to reveal the next number. It’s been used in a few other places including the home screen in the HTC Diamond device, and its physical, realistic style fits well with the iPad, so I set about creating a version for the iPhone and iPad using the built-in Core Animation library. Read on for more details.



I started by thinking about the motions that would be required for the animation. We can break it down as three elements, the top, the bottom and the flipping part. Each of these parts can be represented as a Core Animation Layer (a CALayer). We create them using the class method on CALayer, there’s no additional retain here, as the _toplayer property is retained.

_toplayer = [CALayer layer];

Splitting images

Now we’ve got the layers, we need something to but into them. I didn’t want to create lots of pre-processed images for the top and bottom sections of each number, so instead I wrote a routine to split the images in code, drawing each half into an image context and grabbing a UIImage from it. This is then stored in an array for later use. We can get any of the elements from the array and set it as the content of the layer as required.

// The size of each part is half the height of the whole image
CGSize size = CGSizeMake([img size].width, [img size].height/2);
 
// Create image-based graphics context for top half
UIGraphicsBeginImageContext(size);
 
// Draw into context, bottom half is cropped off
[img drawAtPoint:CGPointMake(0.0,0.0)];
// Grab the current contents of the context as a UIImage 
// and add it to our array
UIImage *top = [UIGraphicsGetImageFromCurrentImageContext() retain];   
[_imagesTop addObject:(id)top];
 
// Now draw the image starting half way down, to get the bottom half
[img drawAtPoint:CGPointMake(0.0,-[img size].height/2)];
// And store that image in the array too
UIImage *bottom = [UIGraphicsGetImageFromCurrentImageContext() retain];   
[_imagesBottom addObject:(id)bottom];
 
UIGraphicsEndImageContext();

Now our _imagesTop and _imagesBottom arrays contains all the images we need, let’s get ‘em moving.

Applying animation


The axes and anchor point of a CALayer
The axes and anchor point of a CALayer
The animation we need to apply to the ‘flipping’ part is a rotation around the bottom of the layer, at the join between the two halves. The default location of the anchor point is the middle of the layer, which would mean the piece would rotate around the middle, but we can easily change it to instead be at the middle in the bottom (for our purposes it could be anywhere on the bottom, as we’re only interested in x-axis rotation):

_fliplayer.anchorPoint = CGPointMake(0.5, 1.0);

I use the CATransform3DMakeRotation function to create a transform around the X axis using the vector [1,0,0]. For the first part of the motion, we go from 0 radians to pi/2 radians (0 to 90 degrees), using an explicit CABasicAnimation object:

CABasicAnimation *topAnim = [CABasicAnimation animationWithKeyPath:@"transform"];
topAnim.duration=0.25;
topAnim.repeatCount=1;
topAnim.fromValue= [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.0, 1, 0, 0)];
float f = -M_PI/2;
topAnim.toValue=[NSValue valueWithCATransform3D:CATransform3DMakeRotation(f, 1, 0, 0)];
topAnim.delegate = self;
topAnim.removedOnCompletion = FALSE;
[_fliplayer addAnimation:topAnim forKey:[NSString stringWithUTF8String:k_TopAnimKey]];

Drawing layer content

Unfortunately a CALayer doesn’t have a “back”, so creating the flip layer is not as easy as it could be. We need to add a step in the process to change the image displayed by the flip layer half way through its fall. We can do this in a variety of ways, I’ve chosen to set a delegate object to perform the drawing of the layer contents:

[_fliplayer setDelegate:_layerHelper];

This means our delegate object (_layerHelper) has its drawLayer method called whenever the layer needs to display its contents. Be wary though, this may not be as often as you think! Core graphics aggressively caches the contents of the layer, and will only call your delegate when absolutely necessary. You can force it to happen by calling setNeedsDisplay, which invalidates the contents of the layer:

[_fliplayer setNeedsDisplay];

I encapsulated this in the helper object itself, by providing a custom implementation of the isTop property setter that calls setNeedsDisplay. At least that way callers don’t have to be aware of this requirement.
The drawLayer method itself simply draws one of two images into the context, depending on whether it’s in ‘top’ mode. A slight further complication is that when drawing the bottom part, the image needs to be inverted to display upside down. This is achieved by applying a translation and scale to the context before drawing the image:

CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0f, r.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);
 
CGContextDrawImage(context, r, [_imgTop CGImage]);
 
CGContextRestoreGState(context);

Avoiding implicit animation

I’ve tried to avoid using implicit animation here, instead using explicit construction of CABasicAnimation objects, because we need some control of when things happen, and the order in which they happen. Normally, it would be easier to just set some property of the view and let the OS manage animating it. Many properties have default transition that are applied whenever they’re changed, so it takes some additional effort to make them change immediately.
In our example we change the contents of the top half and show the flip layer, but we need that to happen immediately so we disable actions within an explicit transaction that we then commit. This gives us the control we need, and avoids the default behaviour of the transition occurring when the message loop next runs.

[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
    forKey:kCATransactionDisableActions];
_toplayer.contents = (id)[[_imagesTop objectAtIndex:[self getNextIndex]] CGImage];
_fliplayer.hidden = NO;
[CATransaction commit];

Getting some perspective

Although the images I’ve used to illustrate this post are isometric, what we really want is a front-on perspective view, so that the falling piece seems to stick out. For this we have to set a sublayerTransform on the view’s inherent layer, by setting an individual element on a transform:

CATransform3D aTransform = CATransform3DIdentity;
float zDistance = 1000;
aTransform.m34 = 1.0 / -zDistance; 
[self layer].sublayerTransform = aTransform;

This gives us a much more realistic look.

Putting it together

Wow, so now we’ve got some appropriately sliced images, some layers and some animations. Let’s put them together to get the final effect.


The animation states (last is same as first)
The animation states (last is same as first)


I’ve used a very simple state machine that moves through 3 states; TopToMiddle, MiddleToBottom, ResetForNext. We can use the animationDidStop delegate as the state transition point. We don’t have to bother determining exactly which animation finished, because we do the same thing (change state) regardless.

- (void)animationDidStop:(CAAnimation *)oldAnimation finished:(BOOL)flag
{
 [self changeState];
}

  • TopToMiddle: show flip layer, and start rotation through 90 degrees
  • MiddleToBottom: change image on flip layer, start rotation through further 90 degrees
  • ResetForNext: change displayed top and bottom layer contents and hide flip layer
Let’s see how it looks in action:

2012年10月8日星期一

Getting symbolicate stack call in logs

Getting symbolicate stack call in logs:
In last version of Xcode we can’t see full crash log.
For resolving this issue we can use next solution:

1. add function to your main class
1
2
3
4
5
void uncaughtExceptionHandler(NSException *exception) {

    NSLog(@"CRASH: %@", exception);

    NSLog(@"Stack Trace: %@", [exception callStackSymbols]);

    // Internal error reporting

}
2. And last thing
1
2
3
4
5
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{  

    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

    // Normal launch stuff

}
Or you can use commands
if you use GDB
1
(gdb) info line *0x2658
or
1
(gdb) bt
And One more Beautiful solution
1. Open the breakpoint navigation in XCode 4 (This looks like a rectangle with a point on the right side)

2. Press the ‘+’ button at the bottom left and add an ‘Exception Breakpoint’. Ensure you break ‘On Throw’ for ‘All’ exceptions.
Now you should get a full backtrace immediately prior to this exception occurring. This should allow you to at least zero in on where this exception is being thrown.
source discussion on stackoverflow one more source
The post Getting symbolicate stack call in logs appeared first on Notes of a Developer.

Debugging Core Data Objects

Debugging Core Data Objects:
If you’re working on an app that uses Core Data, it’s inevitable that you’ll end up in the debugger and need to dig around in the object graph. You’ll also quickly realize that Core Data’s -description of an object isn’t terribly helpful:
(lldb) po myListObj
(List *) $19 = 0x08054ac0 <List: 0x8054ac0> (entity: List; id: 0x8074280 <x-coredata://29B10357-0723-4950-9EB6-E6D7AD6269B9/List/p175> ; data: <fault>)
Core Data’s documentation is excellent, but surprisingly doesn’t cover some of the tricks you can use to examine managed objects in the debugger.
The first trick is to fire a fault on the object using -willAccessValueForKey. After that, you can see what’s really there:
(lldb) po [myListObj willAccessValueForKey:nil]
(id) $20 = 0x08054ac0 <List: 0x8054ac0> (entity: List; id: 0x8074280 <x-coredata://29B10357-0723-4950-9EB6-E6D7AD6269B9/List/p175> ; data: {
    containerId = "8E4652D3-5516-4186-B1C9-DDBE41E108CF";
    createdAt = "2009-10-08 15:17:53 +0000";
    itemContainers = "<relationship fault: 0x8020850 'itemContainers'>";
})
You might also be surprised when you try to access one of the properties of the object:
(lldb) po myListObj.containerId
error: property 'containerId' not found on object of type 'List *'
error: 1 errors parsing expression
Remember that these properties are defined as @dynamic and there’s a lot of work done by Core Data at runtime to provide the implementation. The solution here is to use the KVC accessor -valueForKey: to get the object’s value:
(lldb) po [myListObj valueForKey:@"containerId"]
(id) $26 = 0x08069b60 8E4652D3-5516-4186-B1C9-DDBE41E108CF
Often, you’ll want to examine the relationships between objects. As you can see in the output above, the attribute itemContainers, which is a to-many relationship, is a fault. To fire the fault, get all the objects from the set:
(lldb) po [[myListObj valueForKey:@"itemContainers"] allObjects]
(id) $23 = 0x0d0667b0 <__NSArrayI 0xd0667b0>(
<Container: 0x807a180> (entity: Container; id: 0x801bc50 <x-coredata://29B10357-0723-4950-9EB6-E6D7AD6269B9/Container/p1> ; data: {
    containerId = TestContainer;
    items = "<relationship fault: 0x805b100 'items'>";
    state = "(...not nil..)";
    type = 4;
})
)
Finally, you may be using Transformable attribute types. The state attribute above is an example. If you’d like more information than (...not nil...), use the KVC getter and you’ll see that it’s an empty NSDictionary:
(lldb) po [[[[myListObj valueForKey:@"itemContainers"] allObjects] lastObject] valueForKey:@"state"]
(id) $29 = 0x0807dd30 {
}

(lldb) po [[[[[myListObj valueForKey:@"itemContainers"] allObjects] lastObject] valueForKey:@"state"] class]
(id) $30 = 0x01978e0c __NSCFDictionary
It’s taken me months to learn these tricks, so hopefully this short essay helps you come up to speed more quickly than I did!

Second Set of TouchTargets Code Published

Second Set of TouchTargets Code Published:

All of the code needed to scan in, draw, and manage text strings from font sheets is in and has been published. Chapter 4: Say “Hello, World!”, OpenGL starts us off with a walkthrough of what we want to accomplish with the new font scanner, and how it will work conceptually.
Chapter 5: Building the Importer walks us through the actual code involved in creating the importer.
After that, in Chapter 6: Using the Importer, we think through what our text string class needs to be able to do to work well with the new importer class. We also start to think about coordinate systems and another class to manage all of our text strings.
Chapter 7: Creating the Text Class takes us on a long journey through the creation of the EDTextString class, a complicated but versatile class that allows us to take the data created by the font importer class and actually create and manipulate OpenGL texture-based dynamic text strings.
At the end of Chapter 7, we find that we still have a few pieces missing from our text rendering system, and finish up the effort with the final class, the EDTextStringManager. Chapter 8: Managing Our Text Strings walks through the creation of the final text handling class, and even takes time out to create a new utility class to contain our texture loading code, EDOpenGLTools.
At last, Chapter 9: Finally, OpenGL Says “Hello, World!”, and More takes all of our hard work from chapters 4 through 8 and creates an iPhone “Hello, World!” demo application.
With this set of code, we’re well on our way to finishing the TouchTargets application. All that’s left are the targets, which we’ll tackle in the next set of chapters, the background, and a scoring mechanism.

2012年2月7日星期二

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

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

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


Create this vertical scrolling platformer with Cocos2D!

Create this vertical scrolling platformer with Cocos2D!


Welcome to the final part of the Monkey Jump tutorial! In this series, we are creating a fun vertical scrolling platformer with Cocos2D, TexturePacker and PhysicsEditor.


In Part One on the tutorial series, we introduced the MonkeyJump! game design, created the sprite sheets and shapes we needed, and began coding the game.


In Part Two, we added our hero to the game, made him move and jump, and added some gameplay.


In this third and final part of the series, we will add some performance improvements, add a HUD Layer, and yes – kill the monkey! :]


We’ll be starting with the project where we left off last time. If you don’t have it already, grab the source code for this tutorial series and open up 5-MonkeyJumpAndRun.


All right, time to stop monkeying around and wrap up this tutorial! :]



Too Many Objects!


Playing our game for a while, you’ll see that it gets slower and slower, until it becomes completely unplayable.




There’s a reason for this – as objects continue to fall from the sky, one after another, they bump into the objects already lying around. All of these collisions have to be handled by Box2d. If there are n objects, there are n*(n-1) possible collisions to handle. Box2d uses hashes to make things faster, but you can imagine how dramatically the number of collisions increases as the number of objects increases.


If you watch a statue drop, you’ll see that nearly the entire stack below moves and bounces from impulses passed from the statue down through the stack from one object to another.


To improve the situation, we’re going to convert objects which are some distance below the monkey into static objects. These static objects will still let other objects pile up above them, but they’ll no longer react to the impact. As a result, a falling statue will only affect the top of the stack instead of the complete pile.


Box2d allows objects to go to sleep when they aren’t touched by other objects for some time. We will use this feature to improve performance.


GB2Engine has an iterate method that can be used to iterate all objects with a block. We will use it to create a routine that checks the y-coordinates of all objects and puts to sleep any that are a certain distance below the monkey.


Add the following code to the end of the update selector in GameLayer.mm:



    // 10 - Iterate over objects and turn objects into static objects
// if they are some distance below the monkey
float pruneDistance = 240/PTM_RATIO;
float prune = [monkey physicsPosition].y - pruneDistance;
[[GB2Engine sharedInstance] iterateObjectsWithBlock: ^(GB2Node* n)
{
if([n isKindOfClass:[Object class]])
{
Object *o = (Object*)n;
float y = [o physicsPosition].y;
if(y < prune)
{
// set object to static
// if it is below the monkey
[o setBodyType:b2_staticBody];
}
}
}
];


Compile and test. Note that there are still some situations where things won’t work as expected. For example, if a group of objects pile up like a tower, and the monkey climbs onto the pile, it might happen that a dropping object reaches the pruneDistance and is converted into a static object in mid-air.


The solution is quite simple: only convert objects to static if their speed is low. Change the second if condition in the above code to:



    if((y < prune) &&
([o linearVelocity].LengthSquared() < 0.1))
{...}


Compile and test. Looks good, doesn’t it?


Caught in a Trap


There’s still an issue though – the monkey might still get caught under a pile of objects. Items pile up around him, and he’s not strong enough to break free if there are too many objects above him.


There are several ways to deal with this situation. One is to simply let him die if he’s stuck. Another solution is to “teleport” the monkey above the objects and let him go on playing. That sounds fun, let’s do that!


To make this work, we must be sure that the monkey teleports above all objects. Otherwise, his position might place him directly inside another object and he’ll never break free!


Go into GameLayer.h and add a member variable:



    float highestObjectY;   // y position of the highest object


And make it a property by adding the following line above the “scene” method declaration:



    @property (nonatomic, readonly) float highestObjectY;


Now switch to GameLayer.mm and synthesize the object by adding this line just below the “@implementation” line:



    @synthesize highestObjectY;


Then, replace section #10 in update with the following:



    // 10 - Iterate over objects and turn objects into static objects
// if they are some distance below the monkey
float pruneDistance = 240/PTM_RATIO;
float prune = [monkey physicsPosition].y - pruneDistance;
highestObjectY = 0.0f;
[[GB2Engine sharedInstance] iterateObjectsWithBlock: ^(GB2Node* n)
{
if([n isKindOfClass:[Object class]])
{
Object *o = (Object*)n;
float y = [o physicsPosition].y;
// record the highest object
if((y > highestObjectY) && ([o active]))
{
highestObjectY = y;
}
if((y < prune) &&
([o linearVelocity].LengthSquared() < 0.1))
{
// set object to static
// if it is below the monkey
[o setBodyType:b2_staticBody];
}
}
}
];


The new code determines the highest object location by resetting the highestObjectY with every new check. Note that it only checks active objects. Otherwise, the highest object will always be the object that is waiting to drop.


Switch to Monkey.h and add a new member:



    int stuckWatchDogFrames; // counter to detect if monkey is stuck


Now let’s teleport the monkey above the highest object’s position if he’s been stuck with an object above his head for a certain amount of time. Aadd the following to the end of the updateCCFromPhysics selector:



    // 8 - Check if monkey is stuck
if(numHeadContacts > 0)
{
stuckWatchDogFrames--;
if(stuckWatchDogFrames == 0)
{
// teleport the monkey above the highest object
[self setPhysicsPosition:b2Vec2([self physicsPosition].x,
gameLayer.highestObjectY+2.0)];
}
}
else
{
// restart watchdog
stuckWatchDogFrames = 120; // 2 seconds at 60fps
}


Compile and run. That’s much better! Now, if the monkey is caught in a trap and he can’t push his way out, he will be magically freed.


There are other ways to detect if the monkey is caught. For example, we could check how high the objects are piled, or if the monkey’s speed is low for a certain amount of time. Feel free to try out other detection methods to see which one works best for you.


Putting the Pain on Our Hero


Play the game for a bit and you’ll realize that there isn’t much challenge to this game – the monkey climbs but doesn’t take any damage. Let’s change that.


Open Monkey.h and add a new variable called health to the Monkey class.



    float health;


Also add properties to access the health level and to detect if the monkey is dead:



@property (readonly) float health;
@property (readonly) bool isDead;


Finally, add a define for the maximum health, at the top of the file below the import statements:



    #define MONKEY_MAX_HEALTH 100.0f


Now switch to Monkey.mm and synthesize the health property:



    @synthesize health;


Implement the isDead property by adding the following code above the walk method :



    -(bool) isDead
{
return health <= 0.0f;
}


As you’ll notice, we decide if the monkey is dead or not based on if his health is less than 0 or not.


In the init selector, initialize the health with the maximum value by adding this below the game layer storage code:



    // set health
health = MONKEY_MAX_HEALTH;




Now let’s put the hurt on the monkey by modifying the section with the head collision in beginContactWithObject:



    else if([fixtureId isEqualToString:@"head"])
{
numHeadContacts++;
float vY = [contact.otherObject linearVelocity].y;

if(vY < 0)
{
const float hurtFactor = 1.0;
// reduce health
health += vY*[contact.otherObject mass] * hurtFactor;
if(self.isDead)
{
// set monkey to collide with floor only
[self setCollisionMaskBits:0x0001];
// release rotation lock
[self setFixedRotation:NO];
// change animation phase to dead
[self setDisplayFrameNamed:@"monkey/dead.png"];
}
}
}


Basically, the monkey should get hurt when an object collides with his head. Calculate the damage using the object’s vertical velocity and mass, and reduce the monkey’s health by that amount. This causes damage from fast-dropping objects, but doesn’t harm the monkey if an object is resting above his head. Notice that I also added a hurtFactor so that you can adjust how much the monkey is hurt.


If the monkey dies, he should drop from the scene. In this case, we’ll simply delete all the monkey’s collision flags except for the floor. This will make the monkey fall dead on the floor. We’ll release the rotation lock to let him lie on the floor, and change the monkey’s sprite to dead.png.


Dead monkeys can’t jump – so change the code in the monkey’s jump selector to ignore screen taps if the monkey is dead:



    -(void) jump
{
if((numFloorContacts > 0) && (!self.isDead))
{
...


Disable the updateCCFromPhysics contents by changing section #1, as well:



    -(void) updateCCFromPhysics
{
// 1 - Call the super class
[super updateCCFromPhysics];
// he's dead – so just let him be!
if(self.isDead)
{
return;
}

...


Compile and run, and now you can bring out your evil side – kill the monkey! :]


Restarting the Game


Now the monkey dies, but the objects keep falling and there’s no way to restart the game.


I would suggest restarting two seconds after the monkey’s death. Usually, we’d go to a high score table after a game ends, but that’s too much for this tutorial. A simple restart will suffice.


Add a new variable to GameLayer.h to hold the restart timer:



    ccTime gameOverTimer;  // timer for restart of the level


And add these lines to the beginning of update inside GameLayer.mm:



    if(monkey.isDead)
{
gameOverTimer += dt;
if(gameOverTimer > 2.0)
{
// delete the physics objects
[[GB2Engine sharedInstance] deleteAllObjects];

// restart the level
[[CCDirector sharedDirector] replaceScene:[GameLayer scene]];
return;
}
}


In case of a restart, we simply remove all objects from the GB2Engine and replace the current scene with a new GameLayer.


Compile and run. The level should now restart two seconds after the monkey’s death.


The HUD Layer – Health


Yes, the monkey dies, but no one knows when it’s going to happen! That’s too realistic for me and most other players. Let’s add a health display so that we can keep track of the monkey’s health.


We’re going to represent the monkey’s health with 10 banana icons. Each banana represent 10 points of health.


Create a new file with the iOS\Cocoa Touch\Objective-C class template. Name the class Hud, and make it a subclass of CCSpriteBatchNode. And don’t forget to change the .m extension to .mm. Replace the contents of the Hud.h file with the following:



    #pragma once

#import "Cocos2d.h"

#define MAX_HEALTH_TOKENS 10

@interface Hud : CCSpriteBatchNode
{
CCSprite *healthTokens[MAX_HEALTH_TOKENS]; // weak references
float currentHealth;
}

-(id) init;
-(void) setHealth:(float) health;

@end


The HUD display uses the sprites from the jungle sprite sheet, so we have to derive the HUD from CCSpriteBatchNode in order to have access to the jungle sprite sheet sprites. Additionally, the HUD needs to keep track of the current health (which we will need later) and the sprite representing each point of the monkey’s health. We also need a method to change the current health.


Switch to Hud.mm and replace its contents with the following:



    #import "Hud.h"
#import "Monkey.h"
#import "GMath.h"

@implementation Hud

-(id) init
{
self = [super initWithFile:@"jungle.pvr.ccz" capacity:20];

if(self)
{
// 1 - Create health tokens
for(int i=0; i<MAX_HEALTH_TOKENS; i++)
{
const float ypos = 290.0f;
const float margin = 40.0f;
const float spacing = 20.0f;

healthTokens[i] = [CCSprite spriteWithSpriteFrameName:@"hud/banana.png"];
healthTokens[i].position = ccp(margin+i*spacing, ypos);
healthTokens[i].visible = NO;
[self addChild:healthTokens[i]];
}
}

return self;
}

@end


Here, we initialize the HUD’s CCSpriteBatchNode super class with the sprite sheet.


Then, we iterate through the number of health tokens and create sprites for each of the bananas. We also increase the x-position of each banana to lay it out next to the previous banana.


Finally, add the method to update the health to the end of Hud.mm:



    -(void) setHealth:(float) health
{
// 1 - Change current health
currentHealth = health;

// 2 - Get number of bananas to display
int numBananas = round(MAX_HEALTH_TOKENS * currentHealth / MONKEY_MAX_HEALTH);

// 3 - Set visible health tokens
int i=0;
for(; i<numBananas; i++)
{
healthTokens[i].visible = YES;
}

// 4 - Set invisible health tokens
for(; i<MAX_HEALTH_TOKENS; i++)
{
healthTokens[i].visible = NO;
}
}


In this method, we need to determine the number of bananas to display, make the ones to display visible, and clear the invisible ones. It’s possible for sections #3 and #4 to be implemented with only one loop, but we’re going to extend this code later and so will have that as two separate loops.


Next we need to add the new HUD to the GameLayer. Switch to GameLayer.h and add the predeclaration of the HUD class:



    @class Hud;


Then, add a member variable for the HUD to the GameLayer class:



    Hud *hud;


Switch to GameLayer.mm and import Hud.h at the start of the file:



    #import "Hud.h"


Init the HUD inside the init selector:



    // add hud
hud = [[[Hud alloc] init] autorelease];
[self addChild:hud z:10000];


Finally, update the HUD from inside the update selector by adding this code to the very end:



    // 11 - Show monkey's health in bananas
[hud setHealth:monkey.health];


Compile and test. It works, but I don’t quite like the visuals – I don’t think the bananas should appear and disappear so abruptly. I want them to fade in and out. I also think the monkey’s health should drop over time rather than instantly.



Since setHealth gets called every frame, it won’t be hard to adjust the displayed health level over time.


Open Hud.mm and change the setHealth selector’s section #1 with the following:



    // 1 - Change current health
float healthChangeRate = 2.0f;
// slowly adjust displayed health to monkey's real health
if(currentHealth < health-0.01f)
{
// increase health - but limit to maximum
currentHealth = MIN(currentHealth+healthChangeRate, health);
}
else if(currentHealth > health+0.01f)
{
// reduce health - but don't let it drop below 0
currentHealth = MAX(currentHealth-healthChangeRate, 0.0f);
}
currentHealth = clamp(currentHealth, 0.0f, MONKEY_MAX_HEALTH);


Compile and test. Now the HUD adjusts more slowly, but the bananas still disappear way too quickly. Let’s make them fade and scale in and out.


Replace sections #3 and #4 in setHealth with the following code:



    // 3 - Set visible health tokens
int i=0;
for(; i<numBananas; i++)
{
if(!healthTokens[i].visible)
{
healthTokens[i].visible = YES;
healthTokens[i].scale = 0.6f;
healthTokens[i].opacity = 0.0f;
// fade in and scale
[healthTokens[i] runAction:
[CCSpawn actions:
[CCFadeIn actionWithDuration:0.3f],
[CCScaleTo actionWithDuration:0.3f scale:1.0f],
nil]];
}
}

// 4 - Set invisible health tokens
for(; i<MAX_HEALTH_TOKENS; i++)
{
if(healthTokens[i].visible && (healthTokens[i].numberOfRunningActions == 0) )
{
// fade out, scale to 0, hide when done
[healthTokens[i] runAction:
[CCSequence actions:
[CCSpawn actions:
[CCFadeOut actionWithDuration:0.3f],
[CCScaleTo actionWithDuration:0.3f scale:0.0f],
nil],
[CCHide action]
, nil]
];
}
}


To fade a banana into view, we check if the banana is already visible. If it’s not, we set it to visible, set the scale to be smaller than the actual size and opacity to 0, and then run an action scaling the banana to 1.0 and fading it in. If the banana is already visible, we’ll do nothing since an action might already be running on it.


To fade a banana out of view, we need a sequence action: first scale and fade out, and then set it to invisible using the CCHide action.


Since we can’t use the visible flag to determine if the banana is fading out, we’ll check the number of animations running on the banana. If the number isn’t zero, that means an animation is already running, so we won’t run another one.


Compile and run. Watch for the bananas to fade in on start and fade out when the monkey gets hurt.


Awesome!



The HUD Layer – the Score


Now let’s add a score display to the HUD. For the score, I suggest using the highest point the monkey has reached while standing on an object.


Switch to Monkey.h and add a new variable and property:



    float score;



    @property (nonatomic, readonly) float score;


Switch to Monkey.mm and synthesize the score property at the beginning of the file:



    @synthesize score;


Add the following lines to the end of updateCCFromPhysics:



    // 9 - update score
if(numFloorContacts > 0)
{
float s = [self physicsPosition].y * 10;
if(s> score)
{
score = s;
}
}


Note that we update the score only if it is higher than the current score because sometimes the monkey might drop down to a lower position after climbing higher. We also scale the monkey’s y-value by 10. Otherwise the score increases are fairly low and not very motivating.


Switch to Hud.h. Add a define for the number of score digits:



    #define MAX_DIGITS 5


Add variables to keep the digit sprites and to cache the CCSpriteFrame pointers:



    CCSprite *digits[MAX_DIGITS];  // weak references
CCSpriteFrame *digitFrame[10]; // weak references


Add a method definition to set the score:



    -(void) setScore:(float) score;


Now switch to Hud.mm. The first thing to do here is cache the lookup of the digit sprites. Add the following lines to the end of the init method:



    // 2 - Cache sprite frames
CCSpriteFrameCache *sfc = [CCSpriteFrameCache sharedSpriteFrameCache];
for(int i=0; i<10; i++)
{
digitFrame[i] = [sfc spriteFrameByName:
[NSString stringWithFormat:@"numbers/%d.png", i]];
}

// 3 - Init digit sprites
for(int i=0; i<MAX_DIGITS; i++)
{
digits[i] = [CCSprite spriteWithSpriteFrame:digitFrame[0]];
digits[i].position = ccp(345+i*25, 290);
[self addChild:digits[i]];
}


Here, we use the CCSpriteFrameCache and request the frame for each digit. We’ll store the frame data in the digitFrame array. Then we create sprites for each digit to display and initialize each one to frame 0.


Add the following method to the end of the file – it prints the current score in a character buffer and adjusts the digits displayed according to the digits in the buffer:



-(void) setScore:(float) score
{
char strbuf[MAX_DIGITS+1];
memset(strbuf, 0, MAX_DIGITS+1);

snprintf(strbuf, MAX_DIGITS+1, "%*d", MAX_DIGITS, (int)roundf(score));
int i=0;
for(; i<MAX_DIGITS; i++)
{
if(strbuf[i] != ' ')
{
[digits[i] setDisplayFrame:digitFrame[strbuf[i]-'0']];
[digits[i] setVisible:YES];
}
else
{
[digits[i] setVisible:NO];
}
}
}


Finally, switch to GameLayer.mm and add this code to the end of the update method:



    // 12 - Show the score
[hud setScore:monkey.score];


Compile and test. Check if the score is updated when the monkey climbs higher. The monkey starts with a score of 9 – this is because the floor’s height already adds to the monkey’s score. If you want you can reduce 9 from the score so it starts at 0.


All of the code up to this point is available in the folder 6-Hud.



Getting Hungry


Currently, the monkey gets hurt by the falling bananas but I want them to restore his health when he consumes them.


To enable this, we’ll create a subclass of Object called ConsumableObject. This class gets a bool variable that keeps track as to whether the object was already consumed.


I usually prefer using one file for each class, but since these classes are quite small, I’m going to add it to the end of Object.h (after @end):



    @interface ConsumableObject : Object
{
@protected
bool consumed;
}
-(void)consume;
@end


Similarly, derive Banana and BananaBunch classes by adding the following code after the definition of ConsumableObject:



    @interface Banana : ConsumableObject
{
}
@end

@interface BananaBunch : ConsumableObject
{
}
@end


Now implement the consume method for ConsumableObject in Object.mm. It’s important to add the code below the @end that closes the @implementation for Object:



    @implementation ConsumableObject

-(void) consume
{
if(!consumed)
{
// set consumed
consumed = YES;

// fade & shrink object
// and delete after animation
[self runAction:
[CCSequence actions:
[CCSpawn actions:
[CCFadeOut actionWithDuration:0.1],
[CCScaleTo actionWithDuration:0.2 scale:0.0],
nil],
[CCCallFunc actionWithTarget:self selector:@selector(deleteNow)],
nil]
];

// play the item comsumed sound
// pan it depending on the position of the monkey
// add some randomness to the pitch
[[SimpleAudioEngine sharedEngine] playEffect:@"gulp.caf"
pitch:gFloatRand(0.8,1.2)
pan:(self.ccNode.position.x-240.0f) / 240.0f
gain:1.0 ];
}
}

@end


The consume method checks to see if the object was already consumed. If it wasn’t consumed, then scale the object to 0 and fade it out, and finally, delete the object from the game.


To do this, we create a CCSequence action with a parallel action of CCFadeOut and CCScaleTo, followed by a CCCallFunction. This CCCallFunction calls the deleteNow selector. This selector removes a GB2Node object from the world, both in graphics and physics.


Now, switch to Monkey.h and add the new restoreHealth method:



    -(void)restoreHealth:(float)amount;


Next, switch to Monkey.mm and implement the method at the end of the class:



    -(void) restoreHealth:(float)amount
{
health = MAX(health + amount, MONKEY_MAX_HEALTH);
}


Here, we simply add the new health value, ensuring that it does not exceed the maximum. Just setting the health is enough as the HUD take care of animating the health bar.


We’ll also play a small gulp sound when the monkey swallows the item. To do this, import Monkey.h at the beginning of Object.mm:



    #import "Monkey.h"


Then, implement the beginContactWithMonkey for the Banana and BananaBunch classes below the implementation for ConsumableObject in Object.mm:



    @implementation Banana
-(void) beginContactWithMonkey:(GB2Contact*)contact
{
if(!consumed)
{
Monkey *monkey = (Monkey *)contact.otherObject;
[monkey restoreHealth:20];
[self consume];
}
}
@end

@implementation BananaBunch
-(void) beginContactWithMonkey:(GB2Contact*)contact
{
if(!consumed)
{
Monkey *monkey = (Monkey *)contact.otherObject;
[monkey restoreHealth:60];
[self consume];
}
}
@end


We simply check if the object was already consumed, and if not, call restoreHealth on the Monkey object. The banana restores 20 points, while the banana bunch restores 60 points.


Compile and run. Hey – what’s that? It’s not working!


Objective Thinking


The reason for failure? Bananas and banana bunches are still created as Object classes. The factory method we use in Object.mm does not yet create our new Banana and BananaBunch objects.


Go back to Object.mm and change the randomObject selector to produce Banana and BananaBunch objects:



    +(Object*) randomObject
{
NSString *objName;
switch(rand() % 18)
{
case 0:
// create own object for bananas - for separate collision detection
return [[[Banana alloc] initWithObject:@"banana"] autorelease];

case 1:
// create own object for banana packs - for separate collision detection
return [[[BananaBunch alloc] initWithObject:@"bananabunch"] autorelease];

case 2: case 3: case 5:
...


Compile and test. Nice!


The only thing that bothers me is that the monkey stops when hitting a banana and the bananas bounce off the monkey.


Box2d has two phases during the stepping of its world: a presolve phase and a collision phase. During the presolve phase it is possible to disable collisions between objects. The collision callbacks will get called, but the objects won’t bounce off.


GBox2D wraps this into a selector called presolveContactWith* that can be called on the colliding objects. Within this selector, you can disable the contact.


Add the following selector to ConsumableObject in Object.mm (before the @end marker) – it will fix the collisions for Banana and BananaBunch:



-(void) presolveContactWithMonkey:(GB2Contact*)contact
{
[contact setEnabled:NO];
}


Compile and test. Check if the monkey can eat the banana without getting disturbed or having the banana bounce off him.



Final improvements


Our game is looking awesome! But I still have a few more improvements for you.


The game is a bit unfair right now: the monkey is on the scene and BAM! – a statue kills him instantly. It is a game that can be won more by chance than by skill.


To make the gameplay a bit more even, we’re going to add a drop indicator. It will be a small red bar that shows the position of the next object drop.


Go to GameLayer.h and add the following variable for the drop indicator:



    CCLayerColor *objectHint; // weak reference


Then, add the following initialization code to the very end of the init method of GameLayer.mm:



    // object Hint
objectHint = [CCLayerColor layerWithColor:ccc4(255,0,0,128)
width:10.0f
height:10.0f];
[self addChild:objectHint z:15000];
objectHint.visible=NO;


We create a semi-transparent red box as the drop indicator and set the box dimensions to 10×10 pixels. We’ll resize it later to match the dropping object’s size.


Next, scroll down to just above section #8 in the update selector and add the following code:



    if(nextDrop < dropDelay*0.5)
{
// update object hint
[objectHint setVisible:YES];

// get object's width
float w = nextObject.ccNode.contentSize.width;

// and adjust the objectHint according to this
[objectHint changeWidth:w];
objectHint.position = ccp([nextObject physicsPosition].x * PTM_RATIO-w/2, 310);
}
else
{
[objectHint setVisible:NO];
}


If the nextDrop is less than half of the dropDelay, we set the objectHint to visible and its width to the dropping object’s width. We also set its position centered below the object’s x coordinate.


Compile and run! Check if the object hint appears below the position of the next drop.



One last addition – the theme music! Import SimpleAudioEngine.h at the beginning of GameLayer.mm, if you haven’t done so already:



    #import "SimpleAudioEngine.h"


Add the following lines to the end of the init selector. The music resources have already been added to the project:



    // music
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"tafi-maradi-loop.caf"];


Compile and run.


The final version of this project is in the folder called 7-done.


Where to Go From Here?


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


Congratulations – you finished the tutorial. Looking back, you’ve learned a ton of things:



  • Using TexturePacker to create your sprite sheets

  • Using PhysicsEditor to create your collision shapes

  • Building a physics-based game with collision detection and sound using Box2d

  • Building a HUD layer to display the health and score


I hope you have enjoyed this tutorial! I’d love to hear what you think of the game and the products we used to make it, so keep the questions and comments coming.


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 3 is a post from: Ray Wenderlich