我有一个在 Xcode 中创建的视频游戏应用程序,SpriteKit 和一个“游戏”模板应用程序。我的游戏有一个分数标签,用于跟踪分数并在玩家得分时更新。下面是我为当前分数和高分这两个标签创建的代码。我的应用程序中有更多代码,但我只是想简化它并仅显示与这种情况相关的代码。当我关闭应用程序并重新打开应用程序时,分数会重置为零。但我想要的是即使你关闭应用程序也能保存高分?而且,如果当前分数高于高分,那么如果有意义的话,我希望将高分更新为新分数。
我愿意接受建议。
游戏场景.h
#import <SpriteKit/SpriteKit.h>
@interface GameScene : SKScene <SKPhysicsContactDelegate>
{
NSTimer *timerOne;
NSTimer *timerTwo;
NSInteger HighScore;
NSInteger score;
}
@end
游戏场景.m
-(void)didMoveToView:(SKView *)view {
//SCORELABEL
SKLabelNode *scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"ChalkboardSE-Bold"];
scoreLabel.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.size.height-50);
scoreLabel.fontSize = 30;
scoreLabel.text = @"0";
scoreLabel.fontColor = [SKColor blueColor];
scoreLabel.name = @"scoreLabel";
[self addChild:scoreLabel];
}
-(void) didBeginContact:(SKPhysicsContact *)contact {
//When redblock comes in contact with redball
if (contact.bodyA.categoryBitMask == CollisionCategoryRedBlock &&
contact.bodyB.categoryBitMask == CollisionCategoryRedBall) {
//Update the score label and add 1 to the current score
[self addPoint:1];
}
//if anything else happens it's gameover
else {
[self performGameOver];
}
}
//Method to add a point to the scorelabel
-(void) addPoint:(NSInteger)points {
score += points;
SKLabelNode *scoreLabel = (SKLabelNode*)[self childNodeWithName:@"scoreLabel"];
scoreLabel.text =[NSString stringWithFormat:@"%ld", (long)score];
}
//Gameover method which will show the high score label
-(void) performGameOver {
//HIGHSCORELABEL
SKLabelNode *highScoreLabel = [SKLabelNode labelNodeWithFontNamed:@"ChalkboardSE-Bold"];
highScoreLabel.position = CGPointMake(CGRectGetMidX(self.frame), 100);
highScoreLabel.fontSize = 20;
highScoreLabel.text = [NSString stringWithFormat:@"High Score: %ld", (long)score];
highScoreLabel.fontColor = [SKColor blueColor];
[self addChild:highScoreLabel];
}