4
5

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】iPhoneを傾けてボールを転がす方法

Last updated at Posted at 2023-07-07

はじめに

モーションセンサーを使ってボールを転がす方法を紹介します。

作るもの

デバイスを傾けるとボールが転がるアプリを作ります。

対象者

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

やり方

import SwiftUI
import CoreMotion

struct ContentView: View {

    // ボールの位置
    @State private var ballPosition: CGPoint = .zero
    
    // モーションマネージャー
    private let motionManager = CMMotionManager()

    // 直径
    private let diameter: CGFloat = 50

    var body: some View {
        GeometryReader { geometry in
            Circle()
                .frame(width: diameter, height: diameter)
                .foregroundColor(.red)
                .position(ballPosition)
                .onAppear {

                    // ボールの初期位置を画面の中心にする
                    ballPosition = CGPoint(x: geometry.size.width / 2, y: geometry.size.height / 2)

                    // モーションマネージャーを開始する
                    motionManager.startAccelerometerUpdates(to: .main) { data, _ in
                        guard let data else { return }

                        // x軸とy軸の加速度を取得する
                        let x = data.acceleration.x
                        let y = data.acceleration.y

                        // ボールの位置を更新する
                        let newX = ballPosition.x + CGFloat(x * 10)
                        let newY = ballPosition.y - CGFloat(y * 10)

                        // 半径
                        let radius = diameter / 2

                        // 画面の外に出ないようにする
                        if newX > radius && newX < geometry.size.width - radius {
                            ballPosition.x = newX
                        }
                        if newY > radius && newY < geometry.size.height - radius {
                            ballPosition.y = newY
                        }
                    }
                }
                .onDisappear {
                    // モーションマネージャーを停止する
                    motionManager.stopAccelerometerUpdates()
                }
        }
        .edgesIgnoringSafeArea(.all)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

おわりに

モーションセンサーを使ってボールを転がす方法を紹介しました。これを使ってゲームを作ろうと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?