Last active
December 19, 2017 23:34
-
-
Save bricklife/4bce25d7c6619808278e88c084e26699 to your computer and use it in GitHub Desktop.
Analog Joystick in Playgrounds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: A SpriteKit based Playground | |
import PlaygroundSupport | |
import SpriteKit | |
class JoystickNode: SKNode { | |
private let radius: CGFloat | |
private var baseNode: SKNode | |
private var stickNode: SKNode | |
init(radius: CGFloat) { | |
self.radius = radius | |
self.baseNode = SKShapeNode(circleOfRadius: radius) | |
self.stickNode = SKShapeNode(circleOfRadius: radius / 3) | |
super.init() | |
addChild(baseNode) | |
addChild(stickNode) | |
isUserInteractionEnabled = true | |
} | |
required public init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { | |
guard let touch = touches.first else { return } | |
let location = touch.location(in: self) | |
let distance = sqrt(pow(location.x, 2) + pow(location.y, 2)) / radius | |
if distance <= 1 { | |
stickNode.position = location | |
} | |
} | |
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { | |
guard let touch = touches.first else { return } | |
let location = touch.location(in: self) | |
let distance = sqrt(pow(location.x, 2) + pow(location.y, 2)) / radius | |
if distance <= 1 { | |
stickNode.position = location | |
} else { | |
stickNode.position = CGPoint(x: location.x / distance, y: location.y / distance) | |
} | |
} | |
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { | |
stickNode.position = CGPoint.zero | |
} | |
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { | |
stickNode.position = CGPoint.zero | |
} | |
} | |
class GameScene: SKScene { | |
override func didMove(to view: SKView) { | |
addChild(JoystickNode(radius: 100)) | |
} | |
} | |
let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 640, height: 480)) | |
let scene = GameScene(size: sceneView.frame.size) | |
scene.scaleMode = .aspectFill | |
scene.anchorPoint = CGPoint(x: 0.5, y: 0.5) | |
sceneView.presentScene(scene) | |
PlaygroundSupport.PlaygroundPage.current.liveView = sceneView |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment