I am in the middle of programming a tycoon-like game and have a HUD layer which displays a player's avatar, cash and other details. Thus it needs to be on more than one scene.
However, I am having a problem, once the HUD has been added to the CCNode, it cannot be added again -- so when I move from the Dashboard page to a sub-menu I get an assertion error;
Assertion failure in -[CCMenuItemSprite addChild:z:tag:]
This is pointing to the Avatar image which is part of the HUD.
The HUD layer is basically this;
HUD layer;
- (id)init {
if ((self = [super init]))
{
CGSize winSize = [[CCDirector sharedDirector] winSize];
GameStateManager *state = [GameStateManager sharedGameStateManager];
NSLog(@"listOfPlayers.size = %d", [state.listOfPlayers count]);
// Player 1 data
Player *p = state.humanPlayer;
NSString *txtCash = @"";
// Cash formatting
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setMaximumFractionDigits:0];
if ([p.cash intValue]<1000000) {
txtCash = [NSString stringWithFormat:@"%@", [formatter stringFromNumber:p.cash]];
} else {
double cash = [p.cash doubleValue];
txtCash = [NSString stringWithFormat:@"%@", [state formatCurrencyValue:cash]];
} // end if
[formatter release];
CCLayer *headerLayer = [CCLayer node];
[headerLayer setAnchorPoint:CGPointMake(0, 0.5)];
[headerLayer setPosition:CGPointMake(0, winSize.height-65)];
[headerLayer setContentSize:CGSizeMake(winSize.width, 65)];
// Player avatar
CCSprite *playerSprite = p.spriteOff;
[playerSprite setPosition:CGPointMake(25, 25)];
CCMenuItemSprite *hdrAvatar = [CCMenuItemSprite itemFromNormalSprite:playerSprite selectedSprite:nil target:nil selector:nil];
[hdrAvatar setScale:0.65f];
// Menu
CCMenu *menu = [CCMenu menuWithItems:nil];
[menu setAnchorPoint:CGPointMake(0, 0.5)];
[menu setPosition:CGPointMake(35, 35)];
[menu addChild:hdrAvatar];
[headerLayer addChild:menu];
// add to ccnode
[self addChild:headerLayer];
} // end if
return self;
}
My dashboard page is basic, but calls the HUD like this;
DashboardLayer *layer = [[[DashboardLayer alloc] initWithHUD:hud] autorelease];
-(id) initWithHUD:(HeaderHUDLayer *)hud
{
if ((self = [super init]))
{
NSLog(@"Dashboard page");
_hud = hud;
}
return self;
}
The dashboard has a button, once clicked it goes to a sub-page; whereupon I repeat the process of initWithHUD:hud except that it crashes and returns an assertion error.
I can only think it must be because the avatar sprite has already been added.
I am wondering, what is the correct way to have a HUD layer that will appear on multiple scenes? It would seem that I am doing it wrong.
Thanks