views:

563

answers:

1

I am using the accelerometer to scroll multiple subViews in a UIScrollVIew. I want the view (portrait orientation) to scroll to the right when the user flicks the iPhone to the right, and scroll to the left when the device is flicked to the left.

I thought I could do that just by noting positive or negative x acceleration values, but I see that the values are usually a mixture of positive and negative values. I have set the floor at 1.5g to eliminate non-shake movement, and am looking at the x values over the duration of .5 seconds.

I'm sure there is a trigonometrical method for determining the overall direction of a flick, and that you have to measure values over the duration of the flick motion. I'm also sure that someone has already figured this one out.

Any ideas out there?

Thanks

+2  A: 

OK, worked out a solution. When I detect a shake motion (acceleration greater than 1.5 on the x axis), I start a timer and set a BOOL to true. While the BOOL is true I add acceleration values. When the timer expires, I stop adding acceleration values and determine direction of the shake by the sign of the total acceleration.


- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler {

    if (fabsf(aceler.x) > 1.5)
    {
     shake = YES;
     NSTimeInterval myInterval = .75;
     [NSTimer scheduledTimerWithTimeInterval:myInterval target:self selector:@selector(endShake) userInfo:nil repeats:NO];
     return;
    }

    if(shake)
    {
     totalG += aceler.x;
    }
}

- (void) endShake {
    shake = NO;
    int direction;
    if (totalG isLessThan 0) direction = 1;
    if(totalG isGreaterThan 0) direction = -1;
    [self changePageByShake:direction];
    totalG = 0;
}

Note: I couldn't get the < and > symbols to format correctly in the codeblock above, so I substituted isLessThan and isGreaterThan for the symbols.

Alpinista