I have been trying to get to move an UIImageView with the accelerometer, however I have run into an issue. When I try to smooth out the data and work out the acceleration of the data from the original position, the values return infinity. I'm not really sure what I'm doing wrong!
Here's my code:
- (void)viewDidLoad {
gameObjects = [NSMutableArray arrayWithObjects: nil];
UIImageView* mainChar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[mainChar setCenter:CGPointMake(screenHeight/2, screenWidth/2)];
mainChar.image = [UIImage imageNamed:@"dot.png"];
[self.view insertSubview:mainChar atIndex:2];
[gameObjects addObject:mainChar];
mainChar = nil;
AvData = [NSMutableArray arrayWithObjects: nil];
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 20;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData* accelerationData, NSError* error) {
if (defaultData == nil) {defaultData = accelerationData;}
[self accelerometerUpdate:accelerationData];
}];
}
-(void) accelerometerUpdate:(CMAccelerometerData*)aData {
//Accelerometer Smoothing
[AvData addObject:aData];
if ([AvData count] >= 20) {[AvData removeObjectAtIndex:0];}
float avX = 0;
float avY = 0;
float avZ = 0;
for (int i = 0; i < [AvData count]; i++) {
avX = avX + [[AvData objectAtIndex:i] acceleration].x;
avY = avY + [[AvData objectAtIndex:i] acceleration].y;
avZ = avZ + [[AvData objectAtIndex:i] acceleration].z;
}
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
//Calculate the delta from original device acceleration value
float accX = defaultData.acceleration.x - avX;
float accY = defaultData.acceleration.y - avY;
//float accZ = defaultData.acceleration.z - avZ;
NSLog([NSString stringWithFormat:@"%f", accY]);
UIImageView* mainChar = [gameObjects objectAtIndex:0];
[mainChar setCenter:CGPointMake(mainChar.center.x + accX, mainChar.center.y + accY)];
//accX and accY are infinity for some reason, and so the image disappears!
mainChar = nil;
}
The weird thing is when I NSLog accY, it returns a proper value. What am I doing wrong?
Off the top of my head:
When you get to these lines:
avX = avX/([AvData count] - 1); avY = avY/([AvData count] - 1); avZ = avZ/([AvData count] - 1);
If count == 1 at that point, your code will divide by zero. I would expect that to crash, but if not, the result would be infinity or NAN. (I'd expect NAN, but it might return INF if it doesn't throw an exception. I'd need to test it or look it up to be sure.)