iPhone Accelerometer calibration
How do I properly calibrate the accelerometer for my iPhone game? Currently, when the phone is on a flat surface, the paddle drifts to the left. High or Low Pass filters are not an acceptable solution as I need complete control over the paddle even at low & high values. I know Apple has the BubbleLevel sample but I find it difficult to follow... could someone simplify the process?
My accelerometer code looks like this:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
float acelx = -acceleration.y;
float x = acelx*40;
Board *board = [Board sharedBoard];
AtlasSprite *paddle = (AtlasSprite *)[board.spriteManager getChildByTag:10];
if ( paddle.position.x > 0 && paddle.position.x < 480) {开发者_JAVA技巧
paddle.position = ccp(paddle.position.x+x, paddle.position.y);
}
if ( paddle.position.x < 55 ) {
paddle.position = ccp(56, paddle.position.y);
}
if ( paddle.position.x > 435 ) {
paddle.position = ccp(434, paddle.position.y);
}
if ( paddle.position.x < 55 && x > 1 ) {
paddle.position = ccp(paddle.position.x+x, paddle.position.y);
}
if ( paddle.position.x > 435 && x < 0) {
paddle.position = ccp(paddle.position.x+x, paddle.position.y);
}
}
Thank you!
Okay, problem SOLVED and the solution is so simple I'm actually embarrassed I didn't come up with it sooner. It's as simple as this:
In a "Calibration Button":
//store the current offset for a "neutral" position
calibration = -currentAccelX * accelerationFactor;
In the game time accelerometer function:
//add the offset to the accel value
float x = (-acceleration.y * accelerationFactor) + calibration;
It's as simple as adding the offset. * hides his head *
This is the code I have so far:
//calibrate code from StackOverflow
float calibration = -acceleration.x * accelerationFraction;
float x = (-acceleration.y * accelerationFraction) + calibration;
//My original code
accelerationFraction = acceleration.y*2;
if (accelerationFraction < -1) {
accelerationFraction = -1;
} else if (accelerationFraction > 1) {
accelerationFraction = 1;
}
//API CHANGE set delegate to self
if (orientation == UIDeviceOrientationLandscapeLeft){
accelerationFraction *= -1;
}
精彩评论