user7138913
user7138913

Reputation:

How to make button work in SpriteKit?

I am creating a game, where I have created a Simple UI, and I want the play button to be an action whenever the player hit the play button.

Here is an image: enter image description here

Here is my code as well.

  //I JUST DID THIS. 

  let bgImage = SKSpriteNode(imageNamed: "bg.png")

    bgImage.position = CGPoint(x: self.size.width/2, y: self.size.height/2)

    bgImage.size = self.frame.size

    bgImage.name = "button1"

    self.addChild(bgImage)

Upvotes: 0

Views: 202

Answers (2)

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

By default isUserInteractionEnabled is false so the touch on a scene child like your bgImage is, by default, a simple touch handled to the main (or parent) class (the object is here, exist but if you don't implement any action, you simply touch it)

If you set the userInteractionEnabled property to true on a SKSpriteNode subclass then the touch delegates will called inside this specific class. So, you can handle the touch for the sprite within its class. But you don't need it, this is not your case, you don't have subclassed your bgImage.

You should simply made in your scene:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let node : SKNode = self.atPoint(location)
        if node.name == "button1" {
            print("Tapped")
        }
    }
}

When I look to your image I suspected that your sprite bg.png was composed by background and also the button image: this is very uncomfortable, you should use only an image about your button and , if you want , make another sprite to show your background otherwise you touch ALL (background and button obviusly, not only the button as you needed..).

So, you should separate the image, for example your button could be this:

enter image description here

Upvotes: 1

javimuu
javimuu

Reputation: 1859

Did you try to add: bgImage.isUserInteractionEnabled = true ?

let bgImage = SKSpriteNode(imageNamed: "bg.png")

bgImage.position = CGPoint(x: self.size.width/2, y: self.size.height/2)

bgImage.size = self.frame.size

bgImage.name = "button1"
bgImage.isUserInteractionEnabled = true

self.addChild(bgImage)

Then:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let node : SKNode = self.atPoint(location)
        if node.name == "button1" {
            print("Tapped")
        }
    }
}

Upvotes: 0

Related Questions