我正在游戏层之上创建一个 HUD 层,并在以下代码的帮助下添加一个标签以在该 HUD 中显示分数
// playGame Class
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
playGameLayer *layer = [playGameLayer node];
// add layer as a child to scene
[scene addChild: layer];
// create HUD
id statsHuds = [HUDlayer statsHUDWithBackgroundSprite:HUDBackground withRect:CGRectMake(160,30, 130,60)];
[statsHuds addLabeltoStatsHUDwithName:@"Score" andValue:@"50"];
//[statsHuds setStatusString:@"yewq"];
//[statsHuds updateScorewithValue:199];
// add HUD
[scene addChild: statsHuds];
// return the scene
return scene;
}
- (id)init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init]))
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
[self performSelector:@selector(updateLabel) withObject:nil afterDelay:5];
}
return self;
}
-(void)updateScore
{
HUDlayer *obj = [[HUDlayer alloc]init];
[obj setScoreString:@"100"];
[obj release];
}
// HUDLayer Class
+(id)statsHUDWithBackgroundSprite:(NSString *)spriteName withRect:(CGRect)rect
{
HUDlayer *hud = [[HUDlayer alloc] init];
UIImage *image = [UIImage imageNamed:spriteName];
CCSprite *statsSprite = [CCSprite spriteWithCGImage:image.CGImage key:nil];
[statsSprite setPosition:ccp(rect.origin.x,rect.origin.y)];
[hud addChild:statsSprite];
return [hud autorelease];
}
-(void)addLabeltoStatsHUDwithName:(NSString *)labelName andValue:(NSString *)labelValue
{
[_statusLabel setString:@"no"];// [CCLabelBMFont labelWithString:@"no" fntFile:@"Arial.fnt"];
[_statusLabel setPosition:ccp(160,240)];
[self addChild:_statusLabel];
}
// label added above is not updating
- (void)setScoreString:(NSString *)string
{
_statusLabel.string = string;
NSLog(@"stats string after %@",_statusLabel.string);
}
_statuslbel 在添加到 HUD 后就不会更新,即使 NSlog 返回新值 我可能做错了什么??
最佳答案
在 updateScore 方法中,每次触发此方法时都会创建一个新的 HUDLayer 对象。
相反,您需要引用添加到场景中的 HUDLayer。我建议你给你的 HUDLayer 一个标签:
[scene addChild: statsHuds z:0 tag:HUDTag];
然后在您的 updateScore 方法中,通过其标签访问该 HudLayer 并更新您的分数:
-(void)updateScore
{
HUDLayer * obj = (HudLayer *)[self.parent getChildByTag:HUDTag];
[obj setScoreString:@"100"];
}
希望这对您有所帮助。
关于iphone - 更新 Cocos2d iPhone 中 HUD 上的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9094904/