lundi 23 mars 2015

How to use an AVAudionPlayer soundtrack within a method? iOS

I have an if method that picks out a random background. I have called this method within the didMoveToView so every time the view is loaded, the method will be executed and a random background will be set. If the background first becomes either 0 or 1, the app crashes and i think it's because if the background is NOT the sea then it's trying to stop a soundtrack that hasn't been started yet... Any ideas on how to solve this ?



//PICKS A RANDOM BACKGROUND EACH TIME THE SCENE IS LOADS
-(SKSpriteNode*) pickRandomBackground {

//this pick a random number between 0 and 2 then stores it
NSInteger randomBackground = [Utility randomNumberAt:0 max:3];


SKSpriteNode *background;





//PYRIMID BACKGROUND
if (randomBackground == 0) {


background = [SKSpriteNode spriteNodeWithImageNamed:@"background2"];
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)+20);
background.size = CGSizeMake(self.frame.size.width, self.frame.size.height);



}

//FOREST BACKGROUND
if (randomBackground == 1) {

background = [SKSpriteNode spriteNodeWithImageNamed:@"forestBackground"];
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
background.size = CGSizeMake(self.frame.size.width, self.frame.size.height);
}

//SEA BACKGROUND
if (randomBackground == 2) {



//SKY IMAGE
background = [SKSpriteNode spriteNodeWithImageNamed:@"introbackground.png"];
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
background.size = CGSizeMake(self.frame.size.width, self.frame.size.height);
background.zPosition = -1;

//FOREGROUND SEA
SKSpriteNode *foregroundSea = [SKSpriteNode spriteNodeWithImageNamed:@"foregroundsea"];
foregroundSea.zPosition = 1;
foregroundSea.size = CGSizeMake(self.frame.size.width+200, self.frame.size.width/3.0);
foregroundSea.position = CGPointMake(CGRectGetMidX(self.frame),70);
foregroundSea.anchorPoint = CGPointMake(0.5, 0.0);
[self addChild:foregroundSea];
[foregroundSea runAction:[SKAction waitForDuration:0.7] completion:^{
[foregroundSea runAction:[self waveAnimation]];
}];

//BACKGROUND SEA
SKSpriteNode *backgroundSea = [SKSpriteNode spriteNodeWithImageNamed:@"backgroundSea"];
backgroundSea.zPosition = 0;
backgroundSea.size = CGSizeMake(self.frame.size.width+200, self.frame.size.width/4.0);
backgroundSea.position = CGPointMake(CGRectGetMidX(self.frame),100);
backgroundSea.anchorPoint = CGPointMake(0.5, 0.0);
[self addChild:backgroundSea];
[backgroundSea runAction:[self waveAnimation]];


//WAVE SFX
[self.seaSFX play];
}

if (randomBackground != 2) {
[self.seaSFX stop];
}


background.zPosition = -1;
[self addChild:background];
return background;
}

Aucun commentaire:

Enregistrer un commentaire