0

I am making a game with Sprite kit, I recently added background music to the game and it works, but i want to put a mute button that can allow the player to stop and play the background music while the game is running in case he don't like it. Thanks.

import AVFoundation

class GameScene: SKScene, SKPhysicsContactDelegate {
  var backgroundMusic = SKAudioNode()

func restartScene(){

    self.removeAllChildren()
    self.removeAllActions()
    died = false
    gameStarted = false
    score = 0
    createScene()
}



func createScene(){
backgroundMusic = SKAudioNode(fileNamed: "Musicnamefile.mp3")
    addChild(backgroundMusic)
}





override func didMoveToView(view: SKView) {
    /* Setup your scene here */


    createScene()





       }
Stefan
  • 5,203
  • 8
  • 27
  • 51
JoeD
  • 1
  • 1

1 Answers1

1

To create a button add this in didMoveToView:

    // pause button
    let pauseButton = SKLabelNode()
    let pauseContainer = SKSpriteNode()
    pauseContainer.position = CGPointMake(hud.size.width/1.5, 1)
    pauseContainer.size = CGSizeMake(hud.size.height*3, hud.size.height*2)
    pauseContainer.name = "PauseButtonContainer"        // pause button
    let pauseButton = SKLabelNode()
    let pauseContainer = SKSpriteNode()
    pauseContainer.position = CGPointMake(hud.size.width/1.5, 1)
    pauseContainer.size = CGSizeMake(hud.size.height*3, hud.size.height*2)
    pauseContainer.name = "PauseButtonContainer"
    hud.addChild(pauseContainer)

    pauseButton.position = CGPointMake(hud.size.width/2, 1)
    pauseButton.text="I I"
    pauseButton.fontSize=hud.size.height
    //pauseButton.fontColor = UIColor.blackColor()
    pauseButton.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center
    pauseButton.name="PauseButton"
    hud.addChild(pauseButton)

I'm using the SKLabel to show the pause symbol and a container to increase the touch area. HUD is an rectangle of type SKNode at the top of my game. You have to add the nodes to an element in your game and change the size and position.

To react on the touch:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let node = self.nodeAtPoint(location)

        if (node.name == "PauseButton" || node.name == "PauseButtonContainer") {
            Insert your code here ....
        }
    }
}
Stefan
  • 5,203
  • 8
  • 27
  • 51