开发者

Iphone SDK: move image around with the accelerometer

开发者 https://www.devze.com 2023-03-03 11:09 出处:网络
Im trying to move an image around with the accelerometer by doing that: - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

Im trying to move an image around with the accelerometer by doing that:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    image.center = CGPointMake(acceleration.x, acceleration.y);

}

When i test the app, the image that 开发者_运维技巧is supposed to move around just sits in the x0 y0 position.

I declared the accelerometer, called the .h UIAccelerometerDelegate and so on...

What am i doing wrong?

Thanks in advance! -DD


You do realize that the accelerometer returns, as the name would suggest, measures of acceleration not points on the display? Anyway, what you need to do, is alter the center (not replace it completely), which will allow you to move the image.

Something along these lines:

image.center = CGPointMake(image.center.x + acceleration.x, 
                           image.center.y - acceleration.y);

It is also important to note that the acceleration usually stays between -1 and 1 (unless the user shakes the device), which is due to the gravity being 1G. Therefore you should probably multiply the acceleration.x and .y values with some constant to make the image move a bit faster than about 1 point at a time.

There are additional things you should think about, what if the image is at the edge of the screen? What if the user wants to use the app in some other position than flat on a surface (needs calibration of the accelerometer)?


-(void)moveImage:(id)sender 
{
    [operationView bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];

    [[[(UIPanGestureRecognizer*)sender view] layer] removeAllAnimations];

    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];

    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan)
    {
    firstX = [[sender view] center].x;
    firstY = [[sender view] center].y;
        [imgDeleteView setHidden:FALSE];
    }
    else if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
    {
        [imgDeleteView setHidden:TRUE];
    }

    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
    [[(UIPanGestureRecognizer *)sender view] setCenter:translatedPoint];
 }
0

精彩评论

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