我目前正在使用 cocos2d 为 iPhone 构建游戏,但遇到以下问题:
我有一个名为 GameHUD 的单例类,它在当前关卡场景前显示一个 HUD。偶尔我希望重新绘制 HUD,因此它会根据当前游戏状态进行相应更改。问题是我重绘 HUD 越频繁,帧速率下降得越多。
我猜我未能发布一些资源,但无法弄清楚我必须发布哪些资源。(我对内存管理很陌生。我知道我必须释放使用以下关键字之一创建的对象:“new”、“alloc”、“copy”或“retain”。但 cocos2d 主要生成自动释放对象,因此我不能手动释放它们。如果我错了,请纠正我;))
//static, so it can be called from other classes
+(void)redrawGameHUD{
CGSize winSize = [CCDirector sharedDirector].winSize;
//get reference to background-sprite
CCSprite *background = [[[GameHUD class] sharedHUD] towerBackground];
//remove the child from the HUD, if it exists
[[[GameHUD class] sharedHUD] removeChild:background cleanup:YES];
//create sprite containing the background-image
background = [CCSprite spriteWithFile:@"background.png"];
//add background image to HUD
[[[GameHUD class] sharedHUD] addChild:background];
//load images that should be displayed into an array
NSArray *images = [NSArray arrayWithObjects:@"image1.png", @"image2.png", @"image3.png", @"image4.png", nil];
//remove sprites from HUD before drawing them again.
//the "buildable" array contains all those already drawn sprites
for (CCSprite *entity in [[[GameHUD class] sharedHUD] buildable]) {
[[[GameHUD class] sharedHUD] removeChild:entity cleanup:YES];
}
[[[[GameHUD class] sharedHUD] buildable] removeAllObjects];
//loop over sprites, initialize them and add them to the HUD
for(int i = 0; i < images.count; ++i) {
NSString *image = [images objectAtIndex:i];
CCSprite *sprite = [CCSprite spriteWithFile:image];
//add sprite to HUD and memorize them in the "buildable" array
[[[GameHUD class] sharedHUD] addChild:sprite];
[[[[GameHUD class] sharedHUD] buildable] addObject:sprite];
}
}
因此,每次调用此方法时,帧速率都会下降一点并保持下降。有人可以告诉我,我做错了什么吗?谢谢。