iPhone Accelerometer direction

匆匆过客 提交于 2020-01-07 02:05:07

问题


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:


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.



来源:https://stackoverflow.com/questions/13439915/iphone-accelerometer-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!