Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling background - Sprite Kit

So I tried to create an infinite scrolling background by using this post's solution (Sprite kit side scrolling). However, I would want to make the image repeatable. As you can see in the video below, after the image has finished it's horizontal way, there is some empty gap.. I would like to make the image fill that gap, so repeat it endlessly.

http://www.youtube.com/watch?v=kyLTGz7Irrc or https://vimeo.com/79555900 (password: spritekit)

What I did :

for (int i = 0; i < 2; i++) {
        SKSpriteNode * bg = [SKSpriteNode spriteNodeWithImageNamed:@"bgimage"];
        bg.anchorPoint = CGPointZero;
        bg.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.origin.y);
        bg.name = @"snow1";
        [self addChild:bg];
 }

and in update method:

[self enumerateChildNodesWithName:@"snow1" usingBlock: ^(SKNode *node, BOOL *stop) {
        SKSpriteNode *bg = (SKSpriteNode *) node;
        bg.position = CGPointMake(bg.position.x - 5, bg.position.y);

        if (bg.position.x <= -bg.size.width)
            bg.position = CGPointMake(bg.position.x + bg.size.width * 2, bg.position.y);
    }];
like image 784
Sebyddd Avatar asked Nov 16 '13 14:11

Sebyddd


2 Answers

Anyway, I fixed it. Just in case someone else will need it, this is how I did it:

    // Create 2 background sprites
    bg1 = [SKSpriteNode spriteNodeWithImageNamed:@"bg1"];
    bg1.anchorPoint = CGPointZero;
    bg1.position = CGPointMake(0, 0);
    [self addChild:bg1];

    bg2 = [SKSpriteNode spriteNodeWithImageNamed:@"bg2"];
    bg2.anchorPoint = CGPointZero;
    bg2.position = CGPointMake(bg1.size.width-1, 0);
    [self addChild:bg2];

then in the update method:

    bg1.position = CGPointMake(bg1.position.x-4, bg1.position.y);
    bg2.position = CGPointMake(bg2.position.x-4, bg2.position.y);

    if (bg1.position.x < -bg1.size.width)
        bg1.position = CGPointMake(bg2.position.x + bg2.size.width, bg1.position.y);

    if (bg2.position.x < -bg2.size.width) 
        bg2.position = CGPointMake(bg1.position.x + bg1.size.width, bg2.position.y);
like image 189
Sebyddd Avatar answered Oct 19 '22 23:10

Sebyddd


The original logic that has a for loop works fine with minor changes:

for (int i = 0; i < 2; i++) {
        SKSpriteNode * bg = [SKSpriteNode spriteNodeWithImageNamed:@"bgimage"];
        bg.anchorPoint = CGPointZero;
        bg.position = CGPointMake(i*bg.size.width, 0);
        bg.name = @"snow1";
        [self addChild:bg];
    }

And in the update method:

[self enumerateChildNodesWithName:@"snow1" usingBlock: ^(SKNode *node, BOOL *stop) {
SKSpriteNode *bg = (SKSpriteNode *) node;

bg.position = CGPointMake(bg.position.x - 5, bg.position.y);

if (bg.position.x <= -bg.size.width) {
    bg.position = CGPointMake(bg.position.x + bg.size.width * 2, bg.position.y);
}
}];
like image 36
yaksha Avatar answered Oct 20 '22 00:10

yaksha