开/关按钮逻辑精灵套件

时间:2014-01-05 01:26:51

标签: ios sprite-kit audio

我正在尝试在Sprite Kit中实现音乐/声音效果的开/关按钮。以下是设置按钮的代码:

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

然后在touchesBegan方法中,我将声音图标图像更改为开启或关闭音乐。所以,我的问题是我有正确播放的背景音乐,我只需要一种方法来查看用户是否按下声音图标,然后确保音乐和声音效果不播放,除非用户按下声音图标上。我需要一种方法来使它在多个类之间工作。谢谢!

1 个答案:

答案 0 :(得分:1)

我就是这样做的。在触摸开始时,我会检查你的开/关按钮是否被点击。然后我会切换按钮并更改BOOL变量以播放声音,然后启动/停止正在播放的音乐。 对于你来说,拥有BOOL变量的声音/音乐的单独课程以及播放/暂停音乐和其他音乐相关内容的方法将会很棒。但是你也可以将这些值存储在场景中或其他任何地方,但是在单独的类中播放部分会很棒。 我会这样做,所以你在场景中有2个精灵,一个是 soundOnIcon 其他 soundOffIcon ,你可以在它们不可见时隐藏它们

以下是我要做的一些代码:

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

我就是这样做的。也许它会有所帮助,但如果您需要更多提示或解释,我很乐意提供帮助。 :)