检测iPhone / Apple Watch的物理移动

时间:2016-07-02 14:49:32

标签: iphone physics accelerometer apple-watch core-motion

我正在尝试检测用户执行的移动(向右或向左)。 我们假设用户开始时将手臂伸到他面前,然后将手臂向右或向左移动(距离中心大约90度)。

我已整合CMMotionManager,希望通过startAccelerometerUpdatesToQueuestartDeviceMotionUpdatesToQueue方法了解检测方向。

有人可以建议如何在iPhone上实现这种逻辑,然后在Apple Watch上实现吗?

1 个答案:

答案 0 :(得分:3)

Apple提供了watchOS 3 SwingWatch sample code演示如何使用CMMotionManager()startDeviceMotionUpdates(to:)来计算球拍运动中的挥杆动作。

他们的代码演示了如何检测一秒运动间隔的方向,尽管您可能需要调整阈值以考虑您想要跟踪的运动的特征。

func processDeviceMotion(_ deviceMotion: CMDeviceMotion) {
    let gravity = deviceMotion.gravity
    let rotationRate = deviceMotion.rotationRate

    let rateAlongGravity = rotationRate.x * gravity.x // r⃗ · ĝ
                         + rotationRate.y * gravity.y
                         + rotationRate.z * gravity.z
    rateAlongGravityBuffer.addSample(rateAlongGravity)

    if !rateAlongGravityBuffer.isFull() {
        return
    }

    let accumulatedYawRot = rateAlongGravityBuffer.sum() * sampleInterval
    let peakRate = accumulatedYawRot > 0 ?
        rateAlongGravityBuffer.max() : rateAlongGravityBuffer.min()

    if (accumulatedYawRot < -yawThreshold && peakRate < -rateThreshold) {
        // Counter clockwise swing.
        if (wristLocationIsLeft) {
            incrementBackhandCountAndUpdateDelegate()
        } else {
            incrementForehandCountAndUpdateDelegate()
        }
    } else if (accumulatedYawRot > yawThreshold && peakRate > rateThreshold) {
        // Clockwise swing.
        if (wristLocationIsLeft) {
            incrementForehandCountAndUpdateDelegate()
        } else {
            incrementBackhandCountAndUpdateDelegate()
        }
    }

    // Reset after letting the rate settle to catch the return swing.
    if (recentDetection && abs(rateAlongGravityBuffer.recentMean()) < resetThreshold) {
        recentDetection = false
        rateAlongGravityBuffer.reset()
    }
}