Search code examples
iosobjective-caccelerometer

Acceleration, moving items


I'm now developing a game that uses acceleration to play. I found out how to make my item move, but not to change its 'origin', or more precisely, the origin for acceleration calculation:

In fact, my image moves, and its center is defined like this:

imageView.center = CGPointMake(230, 240);

As you can see, I use landscape mode. But, I want that my image moves "progressively". What i mean by progressively is like in the game Lane Splitter:

You can see that the bike moves, and for example, when he's completely on the left side, the man can orient his iPad horizontally, but the bike doesn't go back in the middle of the screen. I don't know how to do that, because when I try a solution, my image moves, but gets back to the center as soon as my iPhone is horizontal. I understand why, but I don't know how to correct this.

This is my current code:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    int i = 0;
    float current;
    if (i == 0)
    {
        imageView.center = CGPointMake(230, 240);
        current = 240;
        i++;
    }
    //try to modify the origin of acceleration
    imageView.center = CGPointMake(230, current - (acceleration.y*200));
    current = imageView.center.y;      
}

Solution

  • The problem is that i is a local variable. Your code is equivalent to

    imageView.center = CGPointMake(230, 240);
    float current = 240;
    imageView.center = CGPointMake(230, current - (acceleration.y*200));
    [imageView center];
    

    Instead, try something like this (assuming your image view is at the right location on startup):

    CGPoint current = imageView.center;
    current.y -= acceleration.y*200;
    imageView.center = current;
    

    Also bear in mind that acceleration.y is in the device coordinate space; you'll need to compensate for interface rotation if your UI supports multiple orientations.