見出し画像

Swiftでいこう。ゲームつくろ!3

次に惑星が降り注ぐ動作を作って行きます。

func addAsteroid() {
  
       let names = ["asteroid1", "asteroid2", "asteroid3"]
       let index = Int(arc4random_uniform(UInt32(names.count)))
       let name = names[index]
       let asteroid = SKSpriteNode(imageNamed: name)
       let random = CGFloat(arc4random_uniform(UINT32_MAX)) / CGFloat(UINT32_MAX)
       let positionX = frame.width * (random - 0.5)
       asteroid.position = CGPoint(x: positionX, y: frame.height / 2 + asteroid.frame.height)
       asteroid.scale(to: CGSize(width: 70, height: 70))
       addChild(asteroid)
       let move = SKAction.moveTo(y: -frame.height / 2 - asteroid.frame.height, duration: 6.0)
       let remove = SKAction.removeFromParent()
       asteroid.run(SKAction.sequence([move,remove]))
           }
let names = ["asteroid1", "asteroid2", "asteroid3"]

3個の惑星を作って行きます。

let index = Int(arc4random_uniform(UInt32(names.count)))

ランダムに数字をindexに入れて行きます。

let name = names[index
let asteroid = SKSpriteNode(imageNamed: name)

これで惑星をランダムに選んで画像を割り当てて取り出します。

そして上から下向きに移動させます。

let move = SKAction.moveTo(y: -frame.height / 2 - asteroid.frame.height, duration: 6.0)

次に出現場所を決めて行きます。

let random = CGFloat(arc4random_uniform(UINT32_MAX)) / CGFloat(UINT32_MAX)  // ランダムな数字を入れます
let positionX = frame.width * (random - 0.5) // 出現場所を決める

そして、

asteroid.scale(to: CGSize(width: 70, height: 70)) //大きさ調整
addChild(asteroid) // 表示

サイズを調整して画面に表示してやります。

それを動かすタイマーをつくります。

まず、変数タイマーをつくります。

var timer: Timer?

そして、定期的に動かすタイマーの本体です。

timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { _ in
           self.addAsteroid()
       })

関数addAsteroid()を定期的に動かして行きます。withTimeInterval: 1.0 で1秒ごとに更新していきます。更新するたびに惑星が作られていきます。


この記事が気に入ったらサポートをしてみませんか?