LoginSignup
4
1

More than 3 years have passed since last update.

【Swift】 SpriteKit 入門 ③

Last updated at Posted at 2021-01-29

SpriteKitの使い方を解説します。
SpriteKit 入門 ② で画像をドラッグして動かせるようになりました。今回は自機(画像)から弾を発射するようにしていきましょう。
(環境:Xcode12.1  Swift5.3)

弾を発射する

今回使用するのは

  • SKShapeNode
  • SKAction
  • TimeInterval

の3つです。

弾などの図形を描画する際にはSKShapeNodeを使用します。SKActionで図形にアニメーションを追加することができます。一定時間毎に弾を発射させたいので、TimeIntervalも使用しています。それではMyScene.swiftファイルにコードを追加していきましょう。

MyScene.swift
    var image: SKSpriteNode!
    var beforeDragPosition: CGPoint?
    var shoot: SKShapeNode? 
    var lastUpdateTime : TimeInterval = 0

    //省略

    func repeatShoots(){
        self.shoot = SKShapeNode.init(rectOf: CGSize.init(width: 30, height: 30), cornerRadius: 3)
        if let shoot = self.shoot {
            shoot.position = image.position
            shoot.fillColor = SKColor.red
            shoot.lineWidth = 3
            shoot.strokeColor = SKColor.white
            shoot.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
            shoot.run(SKAction.sequence([SKAction.move(by: CGVector(dx: 0, dy: self.size.height), duration: 3),SKAction.removeFromParent()]))
            self.addChild(shoot)
        }
    }

    override func update(_ currentTime: TimeInterval) {
        if (self.lastUpdateTime == 0) {
            self.lastUpdateTime = currentTime
        }
        if (lastUpdateTime + 0.3 <= currentTime) {
            self.repeatShoots()
            lastUpdateTime = currentTime
        }
    }

repeatShoots()では時期から弾を発射させる処理を記述しています。図形の形をSKShapeNode.init()で設定します。ここでは四角にしていますが、円を描画する場合は次のように記述します。

    self.shoot = SKShapeNode.init(circleOfRadius: 15)

以下の部分では弾のアニメーションを設定しています。アニメーションの設定にはSKActionを使用します。複数のアニメーションは配列として追加することができます。

    shoot.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))

    shoot.run(SKAction.sequence([SKAction.move(by: CGVector(dx: 0, dy: self.size.height), duration: 3),SKAction.removeFromParent()]))

またupdate(_ currentTime: TimeInterval)を override して一定時間毎にrepeatShoots()を呼び出すようにしています。

    override func update(_ currentTime: TimeInterval) {
        if (self.lastUpdateTime == 0) {
            self.lastUpdateTime = currentTime
        }
        if (lastUpdateTime + 0.3 <= currentTime) {
            //0.3秒毎にrepeatShoots()を呼び出す
            self.repeatShoots()
            lastUpdateTime = currentTime
        }
    }

実行結果はこのようになります。
SK1.png

次回は敵を表示させて衝突判定を実装していきましょう。

参考

この記事は以下の情報を参考にして執筆しました。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1