我正在尝试检测用户执行的移动(向右或向左)。 我们假设用户开始时将手臂伸到他面前,然后将手臂向右或向左移动(距离中心大约90度)。
我已整合CMMotionManager
,希望通过startAccelerometerUpdatesToQueue
和startDeviceMotionUpdatesToQueue
方法了解检测方向。
有人可以建议如何在iPhone上实现这种逻辑,然后在Apple Watch上实现吗?
答案 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()
}
}