0
votes

I am developing an application in which iPhone will play different sounds when moved (sword). I want to know when iPhone has moved left, right, up or down (sword movement). How can I implement this? I was testing the accelerometer and wrote this code, but it returns the same values if moved left or right. How can I know in which direction is the iPhone moved?

Code:

- (void)accelerometer:(UIAccelerometer *)accelerometer
        didAccelerate:(UIAcceleration *)acceleration
{
    double const kThreshold = 1.0;

    if (fabsf(acceleration.x) > kThreshold) {
        NSLog(@"X+");
    }
}
1

1 Answers

2
votes

Left and right both use acceleration.x

I'm not sure which is which but one is negative x and the other is positive x.

Same for up/down and back/forth.

They all use the same axis (x, y or z) but one direction is positive change and the other is negative change.

By using fabsf you are removing the negative side of the movement.

You need something like...

if (acceleration.x > kThreshold) {
    NSLog(@"X+");
} else if (acceleration.x < kThreshold * -1) {
    NSLog(@"X-");
}

or something instead.