Accelerometer has added an all new dimension to the iPhone. There is no limit on how we can use the accelerometer API in iPhone SDK. The following are some of the well known simple uses of shake/motion detectionNote that in the class which re-implements this method we declare an UIAcceleration object named lastAcceleration and a BOOLEAN variable called shakeDetected. We also need to write a static method named IsDeviceShaking Here's the implementation of function IsDeviceShaking:The above function returns TRUE if the device is shook in any of the 2 axis and the shake is greater than the threshold. One can increase or decrease the sensitivity by changing the threshold. Just put these pieces together and you can detect shake in any screen of your application you want. Please let me know your feedback/suggestions
- Refresh the current view
- Go to next/previous screen
- Start editing
- Shuffle
- and the list goes on
- (void) accelerometer: (UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration { if (self.lastAcceleration) { if (!shakeDetected && IsDeviceShaking(self.lastAcceleration, acceleration, 0.7)) { shakeDetected = YES; //SHAKE DETECTED. WRITE YOUR CODE HERE. } else if (shakeDetected && !IsDeviceShaking(self.lastAcceleration, acceleration, 0.2)) { shakeDetected = NO; } } self.lastAcceleration = acceleration; }
static BOOL IsDeviceShaking(UIAcceleration* last, UIAcceleration* current, double threshold) { double deltaX = fabs(last.x - current.x); double deltaY = fabs(last.y - current.y); double deltaZ = fabs(last.z - current.z); return (deltaX > threshold && deltaY > threshold) || (deltaX > threshold && deltaZ > threshold) || (deltaY > threshold && deltaZ > threshold); }
No comments:
Post a Comment