Calibrate UIAccelerometer?

半世苍凉 提交于 2019-12-08 02:45:41

问题


In my app I use the accelerometer to control the character in my game. Right now I only allow the portrait orientation so the user has to tilt the device to the right or left in order to move the character. That is working fine so far. What I am trying to accomplish now is to 'calibrate' the accelerometer to account for the current tilt the user is playing on. Lets say the user is laying on their side, the values will be skewed since it didn't account for that starting point so they won't be able to control the character. So I am trying to account for that initial tilt amount and then account for it during the game however it is not working.

So I have a button in my non-game view to 'calibrate' the accelerometer and this is the code that it executes:

This is in the IBAction

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0f/30.0f];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];

This is the accelerometer delegate call

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    [[NSUserDefaults standardUserDefaults] setFloat:acceleration.x forKey:@"X-Calibrate"];
    [[UIAccelerometer sharedAccelerometer] setDelegate:nil];
}

Then in my game view in the init I set the iVar calibrationFloat to the value which I set in NSUserDefaults. Then I also have a kFilteringFactor to get rid of the little jitters. So this is the game accelerometer delegate method which sets rollingX equal to everything and then I move the character based upon rollingX:

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    rollingX = ((acceleration.x - calibrationFloat) * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
}

However this is not working, the calibration doesn't seem to do anything and I am not sure why. Does anyone set why this wouldn't be working?


回答1:


I can give you some pointers. The calculation for rollingX is incorrect, it will give out values outside the range -1 - +1, you need a way to detect it hitting the limit and adjust it appropriately. Also simply offsetting one axis will not work. The accelerometer works in 3D space. In order for your calculation to work correctly the phone would always have to be 0 in the z-plane. The further into the z-plane the user rotates the phone, the smaller the readings the device will output on the x-plane. Accelerometers sense gravity, so the planes are fixed relative to this.

In order to carry out an effective calibration you will need to apply a continuous matrix transformation to all 3-axis, as you will need weighted offsets (eg as z increases, pay more attention to y rather than x etc).



来源:https://stackoverflow.com/questions/13225713/calibrate-uiaccelerometer

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