Dev01
Dev01

Reputation: 14149

SKSpriteNode not detecting touch events

I can not get the touchesBegan function to fire. It isn't being called when a user touched the node.

import SpriteKit

class SimpleButton: SKSpriteNode {
    //called when the user taps the button
    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
        println("touches began")
    }

    //called when the user finishes touching the button
    override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
        println("touches ended")
    }

    override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
        println("touches moved")
    }
}

Upvotes: 1

Views: 1770

Answers (1)

Dev01
Dev01

Reputation: 14149

The answer is, You need to enable touches using the userInteractionEnabled parameter.

let imageTexture = SKTexture(imageNamed: "a_button")
let sprite: SimpleButton = SimpleButton(texture: imageTexture)

sprite.userInteractionEnabled = true  // <---  This is required, it defaults to false.

sprite.position = CGPoint(x:CGRectGetMidX(self.frame) - 200, y:CGRectGetMidY(self.frame));
sprite.color = UIColor.blackColor()
sprite.colorBlendFactor = 1.0
self.addChild(sprite)

Upvotes: 4

Related Questions