开发者

Looping moving background objective-C

I am testing a background-loop animation where there will be to images both 1024x768 pixels in dimension, move leftwards, go offscreen, then jump back to the other side, and repeat.

I was able to do this by creating a constant speed for both background image to move (successful), and then I tried the following code to make it jump, but there was a problem:

    if((background.center.x) < -511){
        background.center = CGPointMake(1536, backgrou开发者_StackOverflow中文版nd.center.y);
    }

    if((background2.center.x) < -511){
        background2.center = CGPointMake(1536, background2.center.y);
    }

Somehow this is not working the way I expected. It leaves a few pixels of gap every time, and I am confused why. Does anyone know what's causing this to happen and how to fix it? Thanks!


It seems like you have forgotten to take into account the distance moved. The greater than expression might have been triggered because you moved to far. I guess your movement is larger than 1 pixel/frame.

I am not sure what kind of values that are feeding your movement but I think to take into account the movement you should do something like...

 if ((background.center.x) < -511){
    CGFloat dist = background.center.x + 512;
    background.center = CGPointMake(1536+dist, background.center.y);
 }

 if ((background2.center.x) < -511){
    CGFloat dist = background2.center.x + 512;
    background2.center = CGPointMake(1536+dist, background2.center.y);
 } 


Rather than have the two images move (sort of) independently, I would keep track of a single backgroundPosition variable and then constantly update the position of both images relative to that one position. This should keep everything nice and tidy:

CGFloat const backgroundWidth = 1024;
CGFloat const backgroundSpeed = 2;

- (void)animateBackground {
    backgroundPosition -= backgroundSpeed;
    if (backgroundPosition < 0) {
        backgroundPosition += backgroundWidth;
    }
    background1.center.x = backgroundPosition - backgroundWidth/2;
    background2.center.x = backgroundPosition + backgroundWidth/2;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜