得分系统不能正常工作
问题描述:
我正在尝试在我的比赛中有一个得分系统。每次我打砖头时我都想把分数提高一个。我现在的代码在正确的位置上显示了分数,但是每次碰到砖时,它都不会增加。我真的不知道发生了什么,任何帮助将不胜感激。得分系统不能正常工作
我有我的课程扩展。 SKLabelNode * _lblScore;
这是为了当我的球接触到一块砖头。
- (空)didBeginContact:(SKPhysicsContact *)接触{
//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];
}
答
您似乎没有在代码中的任何位置修改分数。最简单的方法是在设置标签的位置上方添加一行。
[GameState sharedInstance].score += 1; // Increment the score by one.
[_lblScore setText:[NSString stringWithFormat:@"%d", [GameState sharedInstance].score]];
好的但其他所有的东西都不错?我现在需要做的是修改分数? – 2014-12-03 03:28:46
我只是剔除了代码的其余部分,它只有几个部分,因此我会从中着手。 – Moshe 2014-12-03 03:29:24