UIAccelerometer有帮助吗?

时间:2011-09-19 00:33:16

标签: ios accelerometer

在谷歌或两个谷歌之后,我想出了这个代码来保存用户所在的当前位置(所以我可以校准它)并将其保存到NSUserDefaults。这是在我的设置视图中:

//Add code for calibrating accelerometer
        UIAcceleration *acceleration;
        float accelX = (acceleration.x - [[NSUserDefaults standardUserDefaults] floatForKey:@"X-Calibrate"]);
        float accelY = (acceleration.y - [[NSUserDefaults standardUserDefaults] floatForKey:@"Y-Calibrate"]);
        [[NSUserDefaults standardUserDefaults] setFloat:accelX forKey:@"X-Calibrate"];
        [[NSUserDefaults standardUserDefaults] setFloat:accelY forKey:@"Y-Calibrate"];

要重置校准,我会这样做:

[[NSUserDefaults standardUserDefaults] setFloat:0 forKey:@"X-Calibrate"];
    [[NSUserDefaults standardUserDefaults] setFloat:0 forKey:@"Y-Calibrate"];

现在我需要一些帮助。现在我在NSUserDefaults中有这些值。如何将其应用于以下代码,以便“完全”实施校准? 以下是加速度计的代码:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceration {
    AccelPoint.x += (acceration.x*50);
    if (AccelPoint.x < 0) {
        AccelPoint.x = 320;
    }
    if (AccelPoint.x > 320) {
        AccelPoint.x = 0;
    }
    playerSpeed += 0.066;
    AccelPoint.y += playerSpeed;
    Square.center = AccelPoint; 
}

这是一些变量及其定义方式:

CGPoint AccelPoint;
float playerSpeed;

谢谢!

对于加速计代码也快速的小站点问题,我应该使用if-elseif吗?这样会更有效率,还是应该留在if-if?

EDIT1:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceration {
    float accelX = (acceration.x - [[NSUserDefaults standardUserDefaults] floatForKey:@"X-Calibrate"]);
    float accelY = (acceration.y - [[NSUserDefaults standardUserDefaults] floatForKey:@"Y-Calibrate"]);
    AccelPoint.x += (accelX*50);
    if (AccelPoint.x < 0) {
        AccelPoint.x = 320;
    }
    if (AccelPoint.x > 320) {
        AccelPoint.x = 0;
    }
    playerSpeed += 0.066;

    AccelPoint.y += playerSpeed;

    Square.center = AccelPoint;

}

在我的代码中,我没有使用accelY。我应该如何将其应用于我的代码?我稍微清理了一下代码,使其更清晰。

1 个答案:

答案 0 :(得分:1)

不确定您希望如何使用您正在存储的数据,但要访问它只是:

float xCal = [[NSUserDefaults standardUserDefaults] floatForKey:@"X-Calibrate"];
float yCal = [[NSUserDefaults standardUserDefaults] floatForKey:@"Y-Calibrate"];

编辑:

因此,根据您的评论,也许可以尝试这样的事情。

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *) acceration {
    float accelX = (acceration.x - xCal);
    float accelY = (acceration.y - yCal);
    AccelPoint.x += (accelX*50);
    if (AccelPoint.x < 0) {
        AccelPoint.x = 320;
    }
    if (AccelPoint.x > 320) {
        AccelPoint.x = 0;
    }
    playerSpeed += 0.066;
    AccelPoint.y += playerSpeed;
    Square.center = AccelPoint; 
}