How to program smooth movement with an accelerometer, like a maze game on iPhone OS?

I want the image to be able to move realistically with the help of an accelerometer that controls it like any maze game. The following shows what I have so far, but it seems very nervous and generally unrealistic. Images with the ball, it seems, can never stop and make many exciting movements around.

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { deviceTilt.x = 0.01 * deviceTilt.x + (1.0 - 0.01) * acceleration.x; deviceTilt.y = 0.01 * deviceTilt.y + (1.0 - 0.01) * acceleration.y; } -(void)onTimer { ballImage.center = CGPointMake(ballImage.center.x + (deviceTilt.x * 50), ballImage.center.y + (deviceTilt.y * 50)); if (ballImage.center.x > 279) { ballImage.center = CGPointMake(279, ballImage.center.y); } if (ballImage.center.x < 42) { ballImage.center = CGPointMake(42, ballImage.center.y); } if (ballImage.center.y > 419) { ballImage.center = CGPointMake(ballImage.center.x, 419); } if (ballImage.center.y < 181) { ballImage.center = CGPointMake(ballImage.center.x, 181); } 
+4
source share
2 answers

Is there a reason why you cannot use the anti-aliasing filter provided in response to your previous question: How do you use a moving average to filter accelerometer values ​​on iPhone OS ?

+3
source

You need to calculate the current average of the values. To do this, you need to save the last values ​​of n in the array, and then click and squeeze the values ​​from the array when you read the accelerometer data. Here are a few pseudo codes:

 const SIZE = 10; float[] xVals = new float[SIZE]; float xAvg = 0; function runAverage(float newX){ xAvg += newX/SIZE; xVals.push(newX); if(xVals.length > SIZE){ xAvg -= xVals.pop()/SIZE; } } 

You need to do this for all three axes. Play with the SIZE value; the larger it is, the smoother the value, but slow things seem to react. It depends on how often you read the value of the accelerometer. If it is read 10 times per second, then SIZE = 10 may be too large.

+2
source

Source: https://habr.com/ru/post/1301432/


All Articles