Search code examples
iosswiftsprite-kitscene

Is it possible to change scene after tapping a label in iOS?


I have a school project to make a game which is going fine, but I'm struggling to add a back button. I had an idea to click on the word back to take you to the menu but I have no idea how to do it. The normal "button" isn't available as it is going back from a sprite kit scene. Any suggestions or help is appreciated.


Solution

  • Here you go:

    MenuVC.swift:

    enum gameType {
      case easy
      case wobble
      case player2
    }
    
    var currentGameType: gameType = .easy
    var navController = UINavigationController()
    var storyBoard = UIStoryboard()
    
    func presentMenuVC() {
      let menuVC = storyBoard.instantiateViewController(withIdentifier: "menuVC") as! MenuVC
      navController.pushViewController(menuVC, animated: true)
    }
    
    class MenuVC : UIViewController {
    
        @IBAction func Player2(_ sender: Any) {
            moveToGame(game: .player2)
        }
        @IBAction func Easy(_ sender: Any) {
            moveToGame(game: .easy)
        }
        @IBAction func Wobble(_ sender: Any) {
            moveToGame(game: .wobble)
        }
    
        func moveToGame(game: gameType) {
    
          navController = self.navigationController!
          storyBoard = self.storyboard!
    
          let gameVC = self.storyboard?.instantiateViewController(withIdentifier: "gameVC") as! GameViewController
    
            currentGameType = game
    
            self.navigationController?.pushViewController(gameVC, animated: true)
    
        }
    }
    

    NewFile.swift:

    class MainMenuButton: SKSpriteNode {
    
      init(text: String, font: String) {
        let label = SKLabelNode(text: text)
        label.fontName = font
    
        let texture = SKView().texture(from: label)
    
        super.init(texture: texture!, color: .clear, size: texture!.size())
        isUserInteractionEnabled = true
      }
    
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        presentMenuVC()
      }
    
      required init?(coder aDecoder: NSCoder) { fatalError() }
    }
    

    GameScene.swift (add to your didMoveToView func at bottom):

    addChild(MainMenuButton(text: "go back", font: "Chalkduster"))