Skip to content

Instantly share code, notes, and snippets.

@bricklife
Last active December 19, 2017 23:34
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 bricklife/b10f3379807044d776ca85c2b8d5096d to your computer and use it in GitHub Desktop.
Save bricklife/b10f3379807044d776ca85c2b8d5096d to your computer and use it in GitHub Desktop.
Slider in Playgrounds
//: A SpriteKit based Playground
import PlaygroundSupport
import SpriteKit
class SliderNode: SKNode {
private let height: CGFloat
private let width: CGFloat
private var baseNode: SKNode
private var stickNode: SKNode
init(height: CGFloat) {
self.height = height
self.width = height / 10
self.baseNode = SKShapeNode(rectOf: CGSize(width: width, height: height))
self.stickNode = SKShapeNode(rectOf: CGSize(width: width, height: width))
super.init()
addChild(baseNode)
addChild(stickNode)
isUserInteractionEnabled = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func move(location: CGPoint) {
let distance = abs(location.y) / ((height - width) / 2)
if distance <= 1 {
stickNode.position = CGPoint(x: 0, y: location.y)
} else {
stickNode.position = CGPoint(x: 0, y: location.y / distance)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
move(location: location)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
move(location: location)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
move(location: CGPoint.zero)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
move(location: CGPoint.zero)
}
}
class GameScene: SKScene {
override func didMove(to view: SKView) {
addChild(SliderNode(height: 300))
}
}
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