我试图在游戏中使用评分系统。我想每次打砖时都把分数提高一分。我现在的代码显示了正确位置的分数,但每次我打砖时它根本没有增加。我真的不知道发生了什么,我们将非常感谢任何帮助。
我的班级扩展名。 SKLabelNode * _lblScore;
这是因为我的球与砖块接触。
- (void)didBeginContact:(SKPhysicsContact *)contact {
//create placeholder for the "non ball" object
SKPhysicsBody *notTheBall;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
notTheBall = contact.bodyB;
} else {
notTheBall = contact.bodyA;
}
if (notTheBall.categoryBitMask == brickCategory) {
//SKAction *playSFX = [SKAction playSoundFileNamed:@"brickhit.caf" waitForCompletion:NO];
//[self runAction:playSFX];
[_lblScore setText:[NSString stringWithFormat:@"%d", [GameState sharedInstance].score]];
[notTheBall.node removeFromParent];
}
}
这是我为分数标签添加代码的地方。
-(instancetype)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]){
self.backgroundColor = [SKColor colorWithRed:(29.0f/255) green:(29.0f/255) blue:(29.0f/255) alpha:1.0];
//add physics body to scene
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody.friction = 0.0f;
self.physicsBody.categoryBitMask = edgeCategory;
//change gravity
self.physicsWorld.gravity = CGVectorMake(0, 0);
self.physicsWorld.contactDelegate = self;
// Score
_lblScore = [SKLabelNode labelNodeWithFontNamed:@"ChalkboardSE-Bold"];
_lblScore.fontSize = 30;
_lblScore.fontColor = [SKColor colorWithRed:85.0f/255.0f green:191.0f/255.0f blue:154.0f/255.0f alpha:1.0];
_lblScore.position = CGPointMake( 80, 20);
_lblScore.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeRight;
[_lblScore setText:@"0"];
[self addChild:_lblScore];
}
return self;
}
+ (instancetype)sharedInstance
{
static dispatch_once_t pred = 0;
static GameState *_sharedInstance = nil;
dispatch_once( &pred, ^{
_sharedInstance = [[super alloc] init];
});
return _sharedInstance;
}
下面的代码我放在一个单独的类中。它将数据保存在手机中,以便跟踪得分和高分。
- (id) init
{
if (self = [super init]) {
// Init
_score = 0;
_highScore = 0;
// Load game state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id highScore = [defaults objectForKey:@"highScore"];
if (highScore) {
_highScore = [highScore intValue];
}
}
return self;
}
- (void) saveState
{
// Update highScore if the current score is greater
_highScore = MAX(_score, _highScore);
// Store in user defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithInt:_highScore] forKey:@"highScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
答案 0 :(得分:1)
您似乎没有在代码中的任何位置修改分数。修改此方法的最简单方法是在您设置标签的位置上方添加一行。
[GameState sharedInstance].score += 1; // Increment the score by one.
[_lblScore setText:[NSString stringWithFormat:@"%d", [GameState sharedInstance].score]];