Button in SpriteKit in Class GameScene

Hello my friends,


i need a button that execute my func. I created the button but how can i say him when i click it, it has to start a func?


This is my code for the button:

__________________________

func sayHello(){

print("Hello")

}

button.position = CGPoint(x: frame.midX, y: frame.maxY/3)

button.name = "HelloButton"

button.size = CGSize(width: button.size.width * 0.1, height: button.size.height * 0.1)

button.isHidden = false


addChild(button)

___________________________


Or can I somehow connect the Main.Storyboard to the GameScene? Every time I try that, the connection deletes itself.


thanks for your help :-)

Post not yet marked as solved Up vote post of Adi Rs Down vote post of Adi Rs
6.6k views

Replies

Make your button a SpriteKit node. Usually a button in a SpriteKit game is either a SKSpriteNode or SKLabelNode. In your touchesBegan function, call the SKNode function atPoint to determine the node that was touched. Check if the name of the touched node matches the button name. If so, call the function.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     for touch in touches {
          let location = touch.location(in: self)
          let touchedNode = atPoint(location)
          if touchedNode.name == "HelloButton" {
               // Call the function here.
          }
     }
}