3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SpriteKitでタッチしたところにアニメーションを表示する

Last updated at Posted at 2019-08-01

はじめに

SpriteKitで作ったアプリを友人に見てもらっている時に言われました。
「タッチしたところにアニメーションが表示されてタッチした箇所がわかりやすいアプリがあるからそうした方が良い」

日本語で表現するとわかりにくいですが以下のような動作です。

画面収録-2019-08-01-20.06.03.gif

準備するもの

  • クリック時表示される画像
  • SpriteKitが使える状態のプロジェクト

ソースコード


import SpriteKit
import GameplayKit

class GameScene: SKScene {
    let img_circle = SKSpriteNode(imageNamed: "circle.png")  //表示される画像
    let action1 = SKAction.fadeIn(withDuration: 0)           //表示アクション
    let action2 = SKAction.fadeOut(withDuration: 0.5)        //フェードアウトアクション
    var actions = SKAction()                                 //表示とフェードアウトをセットにするシーケンス
    
    
    override func didMove(to view: SKView) {
        self.addChild(img_circle) //タッチ時にシーンに表示される画像をシーンに追加
        
        img_circle.alpha = 0      //タッチされないと表示しないのでalphaを0に設定
        
        //非表示状態の画像を表示してフェードアウトさせるシーケンスを作成
        actions = SKAction.sequence([
            action1,
            action2
            ])
    }
    
    //タッチイベント時処理
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches{
            let location = touch.location(in: self) //タッチされた座標を取得
            img_circle.position = location          //タッチ時に表示する画像の位置を設定
            img_circle.run(actions)                 // アクションを実行させる.
        }
    }
}

さいごに

「withDuration」の「0.5」を調整することでフェードアウトする時間を変更できます。

もっとスッキリ書けるのかどうかわかりませんが、とりあえずそれっぽい動きをしてくれるものができたので忘れないように書き記しておきます。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?