Created
November 4, 2018 21:42
-
-
Save uchcode/60c6124c25b42211c258994b3b3d5c6b to your computer and use it in GitHub Desktop.
Hello SpriteKit
This file contains hidden or 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
import SpriteKit | |
import PlaygroundSupport | |
class Square: SKShapeNode { | |
convenience init(position: CGPoint = .zero, oneSide: CGFloat = 0.0, strokeColor: SKColor = .white) { | |
let c = CGFloat(oneSide * 0.2) | |
let r = CGSize(width: oneSide, height: oneSide) | |
self.init(rectOf: r, cornerRadius: c) | |
self.position = position | |
self.strokeColor = strokeColor | |
let spin = SKAction.repeatForever( | |
.rotate(byAngle: CGFloat(M_PI), duration: 1.0) | |
) | |
let remove = SKAction.sequence([ | |
.wait(forDuration: 0.5), | |
.fadeOut(withDuration: 0.5), | |
.removeFromParent() | |
]) | |
self.run(spin) | |
self.run(remove) | |
} | |
} | |
class Scene: SKScene, SKPhysicsContactDelegate { | |
let label = SKLabelNode(text: "hello world") | |
private func addSquare(positionBy touches: Set<UITouch>, color: SKColor) { | |
for t in touches { | |
let l = t.location(in: self) | |
let n = Square(position: l, oneSide: 100.0, strokeColor: color) | |
addChild(n) | |
} | |
} | |
override func didMove(to view: SKView) { | |
scaleMode = .resizeFill | |
addChild(label) | |
} | |
override func didChangeSize(_ oldSize: CGSize) { | |
label.position = CGPoint(x: size.width / 2, y: size.height / 2) | |
} | |
var lastTime = TimeInterval() | |
override func update(_ currentTime: TimeInterval) { | |
if lastTime + 1.5 > currentTime { | |
return | |
} | |
lastTime = currentTime | |
label.alpha = 1.0 | |
label.run(.fadeOut(withDuration: 1.0)) | |
} | |
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { | |
addSquare(positionBy: touches, color: .green) | |
} | |
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { | |
addSquare(positionBy: touches, color: .blue) | |
} | |
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { | |
addSquare(positionBy: touches, color: .red) | |
} | |
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { | |
addSquare(positionBy: touches, color: .red) | |
} | |
func didBegin(_ contact: SKPhysicsContact) { | |
// Called when two bodies first contact each other. | |
} | |
func didEnd(_ contact: SKPhysicsContact) { | |
// Called when the contact ends between two physics bodies. | |
} | |
} | |
let view = SKView() | |
view.showsDrawCount = true | |
view.showsNodeCount = true | |
view.showsFPS = true | |
view.presentScene(Scene()) | |
PlaygroundPage.current.liveView = view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment