0
votes

I am trying to implement an on/off button in Sprite Kit for the music/sound effects. Here is the code to set up the buttons:

-(void)setUpSoundIcon{
    if (soundOrNoSound == YES) {
        soundIcon = [SKSpriteNode spriteNodeWithImageNamed:[self imageNamed:@"sound"]];
        sound = 2;
    }else if (soundOrNoSound == NO) {
        soundIcon = [SKSpriteNode spriteNodeWithImageNamed:[self imageNamed:@"nosound"]];
        sound = 1;
    }
    soundIcon.name = @"Sound";
    if (screenWidth == 1024 && screenHeight == 768) {
        soundIcon.position = CGPointMake(screenWidth - 50, 50);
    }else if(screenHeight == 320){
        soundIcon.position = CGPointMake(screenWidth - 30, 30);
    }
    [soundIcon setZPosition:2000];
    [self addChild:soundIcon];
}

Then in the touchesBegan method I have the sound icon image change to represent the music on or off. So, my problem is that I have the background music playing correctly, I just need a way to see if the user pressed the sound icon to be off, and then making sure the music and sound effects do not play unless the user pressed the sound icon on. I need a way to do it so that it works between multiple classes too. Thank you!

1

1 Answers

1
votes

This is how I would do it. In touches began I would check if your On/Off button is tapped. Then I would toggle the button and change the BOOL variable for playing the sound and then start/stop music that is playing. It would be great for you to have separate class for sound/music which will have that BOOL variable and methods for playing/pausing music and other music related stuff. But you can also store that values in the scene or anywhere else, but the playing part would be great to have in separate class. And I would to it so you have 2 sprites on the scene, one would be soundOnIcon other soundOffIcon and you can make them hidden when they should not be visible

Here is a bit of code that I would do:

-(void)toggleMusicSound
{
  if([MusicPlayingClass soundOn])
  {
    [MusicPlayingClass setSoundOn:NO];
    [MusicPlayingClass stopAllSounds];//this method will stop playing all continuous music and set other music logic if you want
    [soundOnIcon setHidden:YES];
    [soundOffIcon setHidden:NO];
  }
  else
  {
    [MusicPlayingClass setSoundOn:YES];
    [MusicPlayingClass playSounds];//it will start playing continuous music if it has to, and set other music logic if you want
    [soundOnIcon setHidden:NO];
    [soundOffIcon setHidden:YES];
  }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [touches anyObject];
  CGPoint positionInScene = [touch locationInNode:self];
  //check if your button is tapped
  if(CGRectContainsPoint(soundIcon.frame, positionInScene))
  {
    [self toggleMusicSound];
  }
}

That is how I would do it. Maybe it helps, but if you need some more tips or explanation I would be happy to help. :)