8
4

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 1 year has passed since last update.

【SwiftUI】ポンポン跳ねるボールの作り方

8
Last updated at Posted at 2023-07-08

はじめに

SwiftUIでスーパーボールのように跳ねるボールを作ります。

対象者

SwiftUIの基本的な使い方を知っている人

やり方

import SwiftUI

struct ContentView: View {
    // ボールの位置
    @State private var y: CGFloat = 0

    // ボールの速度
    @State private var velocity: CGFloat = 0

    // アニメーション中かどうか
    @State private var isAnimating: Bool = false
    
    // 重力加速度
    // メートルをポイントに置き換えて考えている
    private let gravity: CGFloat = 9.8

    // 反発係数
    private let bounce: CGFloat = 0.8
    
    // ボールのサイズ
    private let ballSize: CGFloat = 70
    
    // タイマー
    private let timer = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                Color.white
                Circle()
                    .fill(.red)
                    .frame(width: ballSize, height: ballSize)
                    .position(x: geometry.size.width / 2, y: y)
            }
            .onTapGesture {
                // タップしたらアニメーションを開始する
                startAnimation()
            }
            .onReceive(timer) { _ in
                if isAnimating {
                    // 0.01秒ごとにボールの位置を更新する
                    updatePosition(height: geometry.size.height)
                }
            }
        }
        .ignoresSafeArea()
    }
    
    private func startAnimation() {
        if isAnimating {
            // 2回目以降はボールの位置と速度を初期位置に戻す
            y = 0
            velocity = 0 
        } else {
            isAnimating = true
        }
    }
    
    private func updatePosition(height: CGFloat) {
        // 速度に重力加速度を加える
        velocity += gravity

        // ボールの位置を更新する
        // 0.01秒ごとに更新するので、1/100倍する
        y += (velocity / 100)
        
        // ボールが床に着いたら反発する
        if y > height - ballSize / 2 {
            y = height - ballSize / 2
            velocity *= -bounce
        }
    }
}

おわりに

SwiftUIでスーパーボールのように跳ねるボールを作りました。この記事が参考になったと思ってくださった方はいいねとフォローしていただけると励みになります☺️

8
4
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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?