开发者

IPhone accelerometer works even in flat surface

I have an imageView in the view. It moves even if the iphone is still for some time. Why is it so ? Also the image does not respond quickly to the movement of the iphone.

Here is my code written for this:

I have also set the updateInterval and delegate for the accelerometer.

#define kVelocityMultiplier 1000;



-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    if(currentPoint.x < 0)
    {
        currentPoint.x=0;
        ballXVelocity=0;
    }

    if(currentPoint.x > 480-sliderWidth)
    {
        currentPoint.x=480-sliderWidth;
        b开发者_Go百科allXVelocity=0;
    }
    static NSDate *lastDrawTime;
    if(currentPoint.x<=480-sliderWidth&&currentPoint.x>=0)
    {

        if(lastDrawTime!=nil)
        {
            NSTimeInterval secondsSinceLastDraw=-([lastDrawTime timeIntervalSinceNow]);
            ballXVelocity = ballXVelocity + -acceleration.y*secondsSinceLastDraw;

            CGFloat xAcceleration=secondsSinceLastDraw * ballXVelocity * kVelocityMultiplier;

            currentPoint = CGPointMake(currentPoint.x + xAcceleration, 266);
        }
        slider.frame=CGRectMake(currentPoint.x, currentPoint.y, sliderWidth, 10);
    }
    [lastDrawTime release];
    lastDrawTime=[[NSDate alloc]init];
}

Can anyone help me out please ?


You might consider filtering your values the Apple way.

#define kFilteringFactor 0.15

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
accelx = acceleration.x * kFilteringFactor + accelx * (1.0 - kFilteringFactor);
accely = acceleration.y * kFilteringFactor + accely * (1.0 - kFilteringFactor);
accelz = acceleration.y * kFilteringFactor + accelz * (1.0 - kFilteringFactor);}

accelx, accely and accelz are UIAccelerometerValues.

Then you can do something like

ball.position.x += accelx * ballSpeed * deltaDrawingTime;

The movement should be nicer now.


I notice a couple of things in the code

  • The two first if statements to have the position within a certain range should be done just before the slider position is set, otherwise it can happen that the image will be set outside the preferred range.

  • ballXVelocity is calculated as normalized from the acceleration.y value times the delta time. Maybe you should look into multiplying that factor instead of doing the kVelocityMultiplier on the next line.

  • As the accelerometer is very sensitive and it is hard to make perfect fit on the circuitboard one never get perfect value. Instead one should try to have some calibration stage and perhaps use only a valid range similar the two first if statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜