检测 iPhone/Apple Watch 的物理运动

3
我正在尝试检测用户的运动方向(向左或向右)。 我们假设用户先将手臂伸在前面,然后将手臂向左或向右移动(大约偏离中心90度)。
我已经整合了CMMotionManager,并希望了解如何通过startAccelerometerUpdatesToQueue和startDeviceMotionUpdatesToQueue方法检测方向。
有人可以建议如何在iPhone上和Apple Watch上实现这个逻辑吗?
1个回答

4

苹果提供了watchOS 3 SwingWatch示例代码,展示了如何使用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()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接