タイトル : Swift-Playgrounds: センサー MotionDetector-1
更新日 : 2022-11-06
タグ :
swift   

センサーの勉強

iPadを傾けてボールを動かしたかったので、センサーで傾きをひろってきたくて、PlayGroundsの水準器アプリにある MotionDetectorクラスを使ってみる。

pitchがY方向(=縦方向)で、rollがX方向(=横方向)で

@EnvironmentObject を使っています。

画面は以下。pitchとrollの値が、iPadを傾けることによってどんな値になるかを確認するだけ。 画像

ソースは以下です。

ContentView.swift
import SwiftUI

struct ContentView: View {
    // @EnvironmentObjectでmotionDetecotrを参照する
    @EnvironmentObject var detector: MotionDetector
    
    var body: some View {
        VStack {
            HStack {
                Text("pitch(Y,縦方向,上下) : ")
                Text(self.getPitch())
            }
            HStack {
                Text("roll(X,横方向,左右) : ")
                Text(self.getRoll())
            }
        }
    }
    
    // detectorのpitchを返す
    func getPitch() -> (String) {
        return "\(self.detector.pitch)"
    }
    
    // detecotrのrollを返す
    func getRoll() -> (String) {
        return "\(self.detector.roll)"
    }
}
MyApp.swift
import SwiftUI

@main
struct MyApp: App {
    // MotionDetectorを開始。更新間隔は1秒で。
    @StateObject static var motionDetector = MotionDetector(updateInterval: 1.0).started()
    
    var body: some Scene {
        WindowGroup {
            // environmentObject でmotionDetectorを参照出来るようにする
            ContentView().environmentObject(MyApp.motionDetector)
        }
    }
}