Skip to content

Instantly share code, notes, and snippets.

@perezpaya
Created May 9, 2016 12:58
Show Gist options
  • Save perezpaya/125c26e1675a45c1339688cde7dfb9b9 to your computer and use it in GitHub Desktop.
Save perezpaya/125c26e1675a45c1339688cde7dfb9b9 to your computer and use it in GitHub Desktop.
import SpriteKit
enum GamepadButton {
case Left
case Right
}
class Gamepad: SKNode {
private var leftButton: SKSpriteNode!
private var rightButton: SKSpriteNode!
private let disabledAlpha: CGFloat = 0.5
private (set) var movement: GamepadButton?
init(buttonTexture: SKTexture, buttonPadding: CGFloat = 60.0) {
super.init()
setupButtons(buttonTexture, padding: buttonPadding)
userInteractionEnabled = true
}
private func setupButtons(texture: SKTexture, padding: CGFloat) {
setupLeftButton(texture, padding: padding)
setupRight(texture, padding: padding)
}
private func setupLeftButton(texture: SKTexture, padding: CGFloat) {
leftButton = SKSpriteNode(texture: texture)
leftButton.position = CGPointMake(CGRectGetMidX(frame)-padding/2, CGRectGetMidY(frame))
addChild(leftButton)
}
private func setupRight(texture: SKTexture, padding: CGFloat) {
rightButton = SKSpriteNode(texture: texture)
rightButton.position = CGPointMake(CGRectGetMidX(frame)+padding/2, CGRectGetMidY(frame))
rightButton.xScale = rightButton.xScale * -1.0
addChild(rightButton)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
updateMovement(touch)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else { return }
updateMovement(touch)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
cancelMovement()
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
cancelMovement()
}
private func updateMovement(touch: UITouch) {
let touchingNode = nodeAtPoint(touch.locationInNode(self))
if touchingNode == rightButton {
movement = .Right
touchingNode.alpha = 1.0
leftButton.alpha = disabledAlpha
}
else if touchingNode == leftButton {
movement = .Left
touchingNode.alpha = 1.0
rightButton.alpha = disabledAlpha
}
else {
movement = nil
leftButton.alpha = disabledAlpha
rightButton.alpha = disabledAlpha
}
}
private func cancelMovement() {
movement = nil
leftButton.alpha = disabledAlpha
rightButton.alpha = disabledAlpha
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment