How to program smooth movement with the accelerometer like a labyrinth game on iPhone OS?

孤街醉人 提交于 2019-11-30 17:25:35

问题


I want to be able to make image move realistically with the accelerometer controlling it, like any labyrinth game. Below shows what I have so far but it seems very jittery and isnt realistic at all. The ball images seems to never be able to stop and does lots of jittery movements around everywhere.

- (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);
    }

回答1:


Is there some reason why you can not use the smoothing filter provided in response to your previous question: How do you use a moving average to filter out accelerometer values in iPhone OS ?




回答2:


You need to calculate the running average of the values. To do this you need to store the last n values in an array, and then push and pop values off the array when ever you read the accelerometer data. Here is some pseudocode:

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 axis. Play around with the value of SIZE; the larger it is, the smoother the value, but the slower things will seem to respond. It really depends on how often you read the accelerometer value. If it is read 10 times per second, then SIZE = 10 might be too large.



来源:https://stackoverflow.com/questions/2272969/how-to-program-smooth-movement-with-the-accelerometer-like-a-labyrinth-game-on-i

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