Create Button in SpriteKit: Swift

后端 未结 3 2025
礼貌的吻别
礼貌的吻别 2021-02-05 17:42

I want to create a button in SpriteKit or in an SKScene that sends the view to another view controller.

I tried using the \"performSegue with i

3条回答
  •  忘掉有多难
    2021-02-05 18:40

    The simplest solution, but possibly not of the greatest quality, is to use a SpriteNode containing an image and name it. Later, using that scene you can easily program it to transfer the user to the next scene when tapped:

    class GameScene: SKScene {
       let button = SKSpriteNode(imageNamed: "yourImgName")
    
       override func didMoveToView(view: SKView) {
          button.name = "btn"
          button.size.height = 100
          button.size.width = 100
          button.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) + 50)
          self.addChild(button)
    
          //Adjust button properties (above) as needed
          }
    
       override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
          let touch = touches.first
          let positionInScene = touch!.locationInNode(self)
          let touchedNode = self.nodeAtPoint(positionInScene)
    
        if let name = touchedNode.name {
            if name == "btn" {
    
                let yourNextScene = YourNextScene(fileNamed: "YourNextScene")
                self.view?.presentScene(yourNextScene!)
    
              }
          }
       }
    }
    

    Don't forget to replace "YourNextScene" with the actual name of your next scene.

提交回复
热议问题