白い線の後ろからぴょこぴょこするiPhoneアプリのサンプルコードを描いてみます。
import UIKit
import SpriteKit
class ViewController: UIViewController {
weak var scene : SKScene?
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
createBar()
createHop()
}
func setupScene() {
let sv = SKView(frame: view.bounds)
let scn = SKScene(size: sv.bounds.size)
scn.backgroundColor = UIColor(hue: 0.4, saturation: 0.3, brightness: 1, alpha: 1)
sv.presentScene(scn)
view.addSubview(sv)
self.scene = scn
}
func createBar() {
let w = CGRectGetMaxX(view.bounds)
let h : CGFloat = 60.0
let y = [CGRectGetMidY(view.bounds) – 100, CGRectGetMidY(view.bounds) + 50]
for i in 0..<2 {
let bar = SKSpriteNode(color: UIColor.whiteColor(), size: CGSize(width: w, height: h))
bar.position = CGPoint(x: CGRectGetMidX(view.bounds), y: y[i])
bar.zPosition = 10
scene?.addChild(bar)
}
}
func createHop() {
let dx = CGRectGetMaxX(view.bounds) / 4.0
let y = [CGRectGetMidY(view.bounds) – 100, CGRectGetMidY(view.bounds) + 50]
for i in 0..<6 {
let hop = SKSpriteNode(color: UIColor(hue: 0.14, saturation: 0.4, brightness: 0.8, alpha: 1), size: CGSize(width: 40, height: 40))
hop.name = “hop\(i % 2)“
hop.position = CGPoint(x: dx * (CGFloat(i % 3) + 1) , y: y[Int(i/3)])
scene?.addChild(hop)
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
scene?.children
.filter {
var check = false
if let name = ($0 as SKNode).name? {
check = name.hasPrefix(“hop”) && name.hasSuffix(“\(self.count)“)
}
return check
}
.map {
($0 as SKNode).runAction(
SKAction.sequence([
SKAction.moveBy(CGVector(dx: 0, dy: 50), duration: 0.2),
SKAction.waitForDuration(0.3),
SKAction.moveBy(CGVector(dx: 0, dy: –50), duration: 0.2),
])
)
}
count = (count + 1) % 2
}
}