Skip to content

Instantly share code, notes, and snippets.

@Bersaelor
Last active December 8, 2017 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bersaelor/dce900a03942c5a7fc0a3c5919f3fc13 to your computer and use it in GitHub Desktop.
Save Bersaelor/dce900a03942c5a7fc0a3c5919f3fc13 to your computer and use it in GitHub Desktop.
SpriteKit Node functioning as a UIButton like node
//
// ButtonNode.swift
// StARs
//
// Created by Konrad Feiler on 07.12.17.
// Copyright © 2017 Konrad Feiler. All rights reserved.
//
import SpriteKit
class ButtonNode: SKNode {
enum ButtonState {
case normal, highlighted
}
var state = ButtonState.normal {
didSet { updateGraphics() }
}
let defaultSprite: SKSpriteNode
let activeSprite: SKSpriteNode
var action: (() -> Void)?
init(defaultImageName: String, activeButtonImage: String) {
defaultSprite = SKSpriteNode(imageNamed: defaultImageName)
activeSprite = SKSpriteNode(imageNamed: activeButtonImage)
super.init()
updateGraphics()
isUserInteractionEnabled = true
addChild(defaultSprite)
addChild(activeSprite)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateGraphics() {
defaultSprite.isHidden = state != .normal
activeSprite.isHidden = state == .normal
}
weak var currentTouch: UITouch?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
state = .highlighted
currentTouch = touches.first
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
log.debug("touches: \(touches)")
guard let touch = currentTouch, touches.contains(touch) else { return }
let location: CGPoint = touch.location(in: self)
state = defaultSprite.contains(location) ? .highlighted : .normal
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = currentTouch, touches.contains(touch) else { return }
state = .normal
currentTouch = nil
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = currentTouch, touches.contains(touch) else { return }
let location: CGPoint = touch.location(in: self)
if defaultSprite.contains(location) { action?() }
state = .normal
currentTouch = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment