Skip to content

Instantly share code, notes, and snippets.

@gblancogarcia
Last active January 3, 2016 14:27
Show Gist options
  • Save gblancogarcia/ebeba75296874da240c9 to your computer and use it in GitHub Desktop.
Save gblancogarcia/ebeba75296874da240c9 to your computer and use it in GitHub Desktop.
SpriteKit: creating a custom button
import SpriteKit
protocol ButtonNodeResponder: class {
func buttonTriggered(button: ButtonNode)
}
class ButtonNode: SKSpriteNode {
var identifier: String?
var responder: ButtonNodeResponder?
var defaultTexture: SKTexture
var highlightedTexture: SKTexture?
var isHighlighted = false {
didSet {
let highlightedTexture = (self.highlightedTexture != nil) ? self.highlightedTexture : defaultTexture
texture = isHighlighted ? highlightedTexture : defaultTexture
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(defaultTexture: SKTexture, color: UIColor, size: CGSize) {
self.defaultTexture = defaultTexture
let color = UIColor.clearColor()
super.init(texture: defaultTexture, color:color, size: size)
self.userInteractionEnabled = true
}
convenience init(defaultTexture: SKTexture, size: CGSize) {
let color = UIColor.clearColor()
self.init(defaultTexture: defaultTexture, color:color, size: size)
}
convenience init(defaultTexture: SKTexture) {
let color = UIColor.clearColor()
let size = defaultTexture.size()
self.init(defaultTexture: defaultTexture, color:color, size: size)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
isHighlighted = true
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
isHighlighted = false
if containsTouches(touches) {
buttonTriggered()
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
isHighlighted = false
}
private func containsTouches(touches: Set<UITouch>) -> Bool {
guard let scene = scene else { fatalError("Button must be used within a scene.") }
return touches.contains { touch in
let touchPoint = touch.locationInNode(scene)
let touchedNode = scene.nodeAtPoint(touchPoint)
return touchedNode === self || touchedNode.inParentHierarchy(self)
}
}
func buttonTriggered() {
if userInteractionEnabled {
if let responder = self.responder {
responder.buttonTriggered(self)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment