0
votes

I have an object (ball) contacting the ground: the ball is very bouncy & contacts ground more then maybe 7 times.

I've utilized the categoryBitMask & contactTestBitMask and set everything up nicely in -(void)didBeginContact:(SKPhysicsContact *)contact.

I've created a property SKAction to handle sound effects & assigned an audio file to the action:

 self.sfxBounce1 = [SKAction playSoundFileNamed:@"bounce1.caf" waitForCompletion:NO];

I call upon this sfxBounce1 in the didBeginContact. Point is it's all working great. Except one problem is that my ball bounces a lot, but for personal reasons, I need the auddio/SKAction to stop playing after the ball has contacted the ground 3 times.

In game, the ball is still bouncing after 3 times it's just I need the sound to stop playing.

But because the code is in an IF statement in the didBeginContact method, the audio keeps playing and playing after every contact with the ground. I'm still very green in programming, especially with Objective-C.

Below is some code

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    if ((firstBody.categoryBitMask == ballCategory) && (secondBody.categoryBitMask == groundCategory))      //Ball & Ground contact
{
    int random = arc4random() %6; //Random # generator of 7 possibilites.

    switch (random) //Generated # represents a case, which in turn initiates a bounce sound upon contact.
    {
        case 0:
            [self runAction:self.sfxBounce1];
            break;
        case 1:
            [self runAction:self.sfxBounce2];
            break;
        case 2:
            [self runAction:self.sfxBounce3];
            break;
        case 3:
            [self runAction:self.sfxBounce4];
            break;
        case 4:
            [self runAction:self.sfxBounce5];
            break;
        case 5:
            [self runAction:self.sfxBounce6];
            break;
        case 6:
            [self runAction:self.sfxBounce7];
            break;
    }

    [self deleteNode];
}

I can't figure out what code to type in each of the 6 cases (between [self runAction:self.sfxBounce1]; & break;) that will stop the action after a set amount of bounces/contacts with the ground.

1
Thank you for editing my question LearnCocos2D - Krekin

1 Answers

1
votes

At the top in your @interface create an int you can reference throughout your code:

property (nonatomic) int bounceCount;

Here is an updated version of your didBeginContact:

-(void)didBeginContact:(SKPhysicsContact *)contact
{

if ((firstBody.categoryBitMask == ballCategory) && (secondBody.categoryBitMask == groundCategory))      //Ball & Ground contact
{
    self.bounceCount++;
    if(self.bounceCount>3)
       return;

     //Your Code

}
}