Scrolling Background issues

Hey all,

I’m developing a prototype for iOS and I’m new to cocos2d. I created a simple scrolling background class that takes the width, height and an array of CCSpriteFrames and performs a horizontal scroll. However, there is always a small gap in between the images. If I slow down the frame rate I can actually see the gap expanding and contracting as it travels across the screen. Also, when on the device I get a whole lot of tearing and other texture glitchiness. Here’s the implementation for ScrollingBackground:

void ScrollingBackground::init(float scrollWidth, float scrollHeight, CCMutableArray *frames)
{
    m_scrollWidth = scrollWidth;
    m_scrollHeight = scrollHeight;
    m_frames = frames;

    //setup the sprites with the first 2 images
    m_sprite1 = CCSprite::spriteWithSpriteFrame(m_frames->getObjectAtIndex(0));
    m_sprite2 = CCSprite::spriteWithSpriteFrame(m_frames->getObjectAtIndex(1));

    //add the sprites to the sprite sheet
    this->addChild(m_sprite1);
    this->addChild(m_sprite2);
}

void ScrollingBackground::update(ccTime dt)
{    
    m_offset += m_scrollSpeed * dt;

    if(m_offset > m_scrollWidth)
    {
        swapSprites();

        m_offset = 0;
    }

    float sprite1X = -m_offset + m_scrollWidth / 2;
    float sprite2X = m_scrollWidth - m_offset + m_scrollWidth / 2;

    m_sprite1->setPosition(ccp(sprite1X, m_scrollHeight / 2));
    m_sprite2->setPosition(ccp(sprite2X, m_scrollHeight / 2));
}

void ScrollingBackground::swapSprites()
{
    CCSprite *temp;

    temp = m_sprite1;
    m_sprite1 = m_sprite2;
    m_sprite2 = temp;
}

Thanks for any help you can give.

Cheers,

This code for horizontal infinite scroller just works. Hope it helps.

Theoretically…

To have a perfectly seamless background you could just use one sprite as the background.
Then make it’s rectangle the size of the screen and tell the texture to repeat.
To scroll just change the anchor point of the texture as you move. You wont need to keep track of a bunch of sprites and i think it will be lighter in memory.

This thread shows how to repeat a texture on a sprite.
http://www.cocos2d-x.org/boards/6/topics/12694

CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage("pic.png");
ccTexParams params = {GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT};
texture->setTexParameters(&params);

CCSprite *sprite = CCSprite::spriteWithTexture(texture, CCRectMake(0, 0, 90, 90));

@MarcRenaud The texture repeat approach needs a POW2 size texture, I think. Which you then scale to your size of course. I don’t think that 2 sprites with ONE texture is memory heavy. Let’s hope the texture cache just works:)