mardi 2 décembre 2014

score system not working

I'm trying to have a scoring system in my game. I want to increase the score by one every time I hit a brick. The code I have now shows the score at the correct position but every time I hit a brick it doesn't increase at all. I don't really know what's going on, any help would be greatly appreciated.


I have the in my class extension. SKLabelNode *_lblScore;


This is for when my ball comes in contact with a brick.


-(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];
}
}


This is where I put the code for the score label.



-(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;
}


The code below I put in a separate class. It keeps the data in the phone so it keeps track of score and high score.



- (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];
}



Aucun commentaire:

Enregistrer un commentaire