Apple은 watchOS 3 SwingWatch sample code을 제공하여 CMMotionManager()
및 startDeviceMotionUpdates(to:)
을 사용하여 라켓 스포츠의 스윙을 계산하는 방법을 보여줍니다.
코드는 1 초 간격의 움직임을 감지하는 방법을 보여 주지만, 추적하려는 움직임의 특성을 설명하기 위해 임계 값을 조정해야 할 수도 있습니다.
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()
}
}