SpriteKit を用いて 田代まさしを左右に動かす feat. Playground


LL脳の悩み

  • ビルドが苦痛
  • そんな僕にも Playground のおかげで気軽に Swift を楽しむ環境が出来た
  • しかしながら SpriteKit を触る上では SpriteKit API を覚えないといけない
    • 何回もビルドするのがダルい => SpriteKit API 離れが発生
  • ビルドくらい我慢しろという声は必死に耳を塞ぐことにする

というわけで

せっかくだから 俺はこの赤の SpriteKit を用いて田代まさしを動かすことを選ぶぜ!

Result

How to

コード

田代まさし.swift

import SpriteKit
import XCPlayground


let sceneWidth = 500
let sceneHeight = 200

func setTashiro(scene: SKScene) -> Void {
    let tashiro = SKSpriteNode(imageNamed: "tashiro")
    let moveShipLeft = SKAction.moveByX(-650, y: 0, duration: 4)
    let moveShipRight = SKAction.moveByX(650, y: 0, duration: 4)
    let tashiroSequence = SKAction.sequence([moveShipLeft, moveShipRight])
    let tashiroLoop = SKAction.repeatActionForever(tashiroSequence)

    tashiro.xScale = -1.0;
    tashiro.position = CGPoint(x: 560, y: 50)
    tashiro.runAction(tashiroLoop)
    scene.addChild(tashiro)
}

// View and scene setup
let skView = SKView(frame: CGRect(x: 0, y: 0, width: sceneWidth, height: sceneHeight))
let skScene = SKScene(size: CGSize(width: sceneWidth, height: sceneHeight))
//skScene.backgroundColor = CGColor.whiteColor()

setTashiro(skScene)
skView.presentScene(skScene)

// Showing the result in our timeline
XCPShowView("Live SKView : Gotanda", view: skView)

PlayGround ファイル

  • こちら からダウンロード出来ます

ポイント

利用する画像ファイルを追加するには?

  • PlayGround の ここをクリックして左のペインを開きます

  • 画像をドラッグアンドドロップします

  • すると、普通に SpriteKit で使っているAPIのようにリソースを利用できるようになります。

Reference

僕は以下の記事を参考にして、PlayGround で動かすのを勉強しました。