Search code examples
swiftskscene

How do I run a function in my GameScene when a contact occurs in my level1Scene in Swift Spritekit?


So I have this function in my GameScene and its a button for level 2 and the only way it could appear in my GameScene is when a contact occurs between the HeroCategory and GoldKeyCategory in my level1Scene. How would I call the levelTwoButton function when a contact occurs between those two categories? Does that make sense? Im kind of stuck right now and need help. Thanks!

EDIT: I want the level 2 button to show up in my GameScene because thats my main menu, not the level1Scene.

// GameScene

func unlockLevelTwo() {

let fadeIn = SKAction.fadeInWithDuration(1.0)

levelTwoButton.position = CGPointMake(self.size.width / 2.0, self.size.height / 2.2)
levelTwoButton.zPosition = 20
levelTwoButton.setScale(0.8)
levelTwoButton.alpha = 0
levelTwoButton.runAction(fadeIn)
levelTwoButton.name = "leveltwobutton"
addChild(levelTwoButton)
}



//levelScene

if firstBody.categoryBitMask == HeroCategory && sixthBody.categoryBitMask == GoldKeyCategory{
   GameScene().unlockLevelTwo()
    runAction(playLevelCompleteSound)
    println("you win and level two button unlocked in the main menu!!!!!")
}

Solution

  • You can use NSUserDefaults which remember your sprite collision like in your levelScene you can store it like:

    if firstBody.categoryBitMask == HeroCategory && sixthBody.categoryBitMask == GoldKeyCategory{
    GameScene().unlockLevelTwo()
    runAction(playLevelCompleteSound)
    println("you win and level two button unlocked in the main menu!!!!!")
    
    NSUserDefaults().setBool(true, forKey: "Leavel2")
    
    }
    

    after that in your GameScene in your didMoveToView method read that every time when your view loads this way:

     override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        let unlockLeavel2 = NSUserDefaults().boolForKey("Leavel2")
    
        if unlockLeavel2 {
    
            unlockLevelTwo()
        }
    }
    

    And this will store even if you quit from app.

    Hope this will help.