Search code examples
iosobjective-ccocos2d-iphonespritebuilder

Gaps in cocos2d infinite looping game


I am using this code to implement infinite looping, but I'v got gaps for 1-2 seconds every time the offscreen image coordinates are changed. Why do they appear? How to fix it? I am also using SpriteBuilder.

#import "MainScene.h"
static const CGFloat scrollSpeed =100.f;
@implementation MainScene{
 CCPhysicsNode *_world; 
    CCNode *_oneb;
    CCNode *_twob;
       NSArray *_bb;


}
- (void)didLoadFromCCB {
    _bb = @[_oneb, _twob];
}

-(void)update:(CCTime)delta{
  _world.position=ccp(_world.position.x - (scrollSpeed * delta), _world.position.y  ); // moving world
    for (CCNode *ground in _bb) {
        // get the world position of the ground
        CGPoint groundWorldPosition = [_world convertToWorldSpace:ground.position];
        // get the screen position of the ground
        CGPoint groundScreenPosition = [self convertToNodeSpace:groundWorldPosition];
        // if the left corner is one complete width off the screen, move it to the right
        if (groundScreenPosition.x <= (-1 * ground.contentSize.width)) {
            ground.position = ccp(ground.position.x + 2 * ground.contentSize.width, ground.position.y);
        }
    }
}

@end

EDIT: I changed -1 to -0.5. Works fine!

enter image description here

enter image description here


Solution

  • Seems like you are using small image for iPhone 3.5-inch on iPhone 4-inch simulator. What resolution of your background image?

    EDIT: In my game I have an infinite loop, too. Maybe my code may help you? First background sprite should be 1137x640, second 1136x640. And you will never have gaps again! Hope it helps.

    init method:

        backgroundSprite = [CCSprite spriteWithFile:@"background.png"];
        backgroundSprite.anchorPoint = ccp(0,0);
        backgroundSprite.position = ccp(0,0);
        [self addChild:backgroundSprite z:0];
    
        backgroundSprite2 = [CCSprite spriteWithFile:@"background2.png"]; 
        backgroundSprite2.anchorPoint = ccp(0,0);
        backgroundSprite2.position = ccp([backgroundSprite boundingBox].size.width,0);
        [self addChild:backgroundSprite2 z:0];
    

    tick method:

    backgroundSprite.position = ccp(backgroundSprite.position.x-1,backgroundSprite.position.y);
    backgroundSprite2.position = ccp(backgroundSprite2.position.x-1,backgroundSprite2.position.y);
    
    if (backgroundSprite.position.x<-[backgroundSprite boundingBox].size.width) {
        backgroundSprite.position = ccp(backgroundSprite2.position.x+[backgroundSprite2 boundingBox].size.width,backgroundSprite.position.y);
    }
    
    if (backgroundSprite2.position.x<-[backgroundSprite2 boundingBox].size.width) {
        backgroundSprite2.position = ccp(backgroundSprite.position.x+[backgroundSprite boundingBox].size.width,backgroundSprite2.position.y);
    }