|
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) |
|
} |
|
} |
|
} |
|
} |