Search code examples
objective-ccocos2d-iphonensmutablearrayccspriterepeat

How to avoid a time lapse when the images are repeated?


i have 3 images and i would like to repeat them, one after the other. When the layer has moved to the left, the first image is not visible anymore and this image takes its new position just after the last image to the right, so that the first image becomes the third one, and the animation is repeated.

My problem is, there is a little time lapse sometimes, i think it happens when the first image is removed and put to the third position. We barely notice it, but it is sort of "pausing" the animation for 0.1 sec and i would like to avoid this.

Would you know how? I have tried with this code (remove the image and insert it again), or just by replacing with replace...atIndex but i have got the same problem. The code is :

if (offsetParam <= offset1-spriteWidth){
        CCSprite *temp = [[sprites objectAtIndex:0] retain];
        [sprites removeObjectAtIndex:0];
        [sprites addObject:temp];
        temp.position = ccp(-offset1+(2*spriteWidth), temp.position.y);
        [temp release];

        offset1 -= spriteWidth;
 }

Any idea ?

Thanks


EDIT: with a counter, the object does not move? (i have tried with a "retain" just in case, but with or without it, i have got the same result)

if (rightDirection){
    //RIGHT
    CCLOG(@"offsetParam %f, offset1-spriteWidth %f", offsetParam, offset1-spriteWidth);
    if (offsetParam < offset1-spriteWidth){ //move the block to the right

        CCSprite *temp = [[grasses objectAtIndex:counterGrass] retain];
        counterGrass++;
        if (counterGrass>2) counterGrass = 0;
        temp.position = ccp(offset1+(2*spriteWidth), temp.position.y);//does not work
        [temp release];
        offset1 -= spriteWidth;
    }

Solution

  • Is "sprites" of type CCArray or NSMutableArray? Because CCArray has a serious performance issue with removeObjectAtIndex, particularly if the index is low (at the beginning of the array) as in your case.

    You could try switching to NSMutableArray and see if that helps.

    Alternatively, avoid using remove and add because it's superfluous. Instead use an index counter that tells you which array index is the first sprite. When the index is >= the number of items in the sprites array, reset it to 0.