Posted By

sag333ar on 11/25/10


Tagged

iphone UIAccelerometer


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

sag333ar
yannxou
Tintenklecks


UIAccelerometer Handle - Shake


 / Published in: Objective C
 

URL: http://stackoverflow.com/questions/150446

grabbed from here - http://stackoverflow.com/questions/150446

  1. // Ensures the shake is strong enough on at least two axes before declaring it a shake.
  2. // "Strong enough" means "greater than a client-supplied threshold" in G's.
  3. static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
  4. double
  5. deltaX = fabs(last.x - current.x),
  6. deltaY = fabs(last.y - current.y),
  7. deltaZ = fabs(last.z - current.z);
  8.  
  9. return
  10. (deltaX > threshold && deltaY > threshold) ||
  11. (deltaX > threshold && deltaZ > threshold) ||
  12. (deltaY > threshold && deltaZ > threshold);
  13. }
  14.  
  15. @interface L0AppDelegate : NSObject <UIApplicationDelegate> {
  16. BOOL histeresisExcited;
  17. UIAcceleration* lastAcceleration;
  18. }
  19.  
  20. @property(retain) UIAcceleration* lastAcceleration;
  21.  
  22. @end
  23.  
  24. @implementation L0AppDelegate
  25.  
  26. - (void)applicationDidFinishLaunching:(UIApplication *)application {
  27. [UIAccelerometer sharedAccelerometer].delegate = self;
  28. }
  29.  
  30. - (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
  31.  
  32. if (self.lastAcceleration) {
  33. if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {
  34. histeresisExcited = YES;
  35.  
  36. /* SHAKE DETECTED. DO HERE WHAT YOU WANT. */
  37.  
  38. } else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {
  39. histeresisExcited = NO;
  40. }
  41. }
  42.  
  43. self.lastAcceleration = acceleration;
  44. }
  45.  
  46. // and proper @synthesize and -dealloc boilerplate code
  47.  
  48. @end

Report this snippet  

You need to login to post a comment.