0
votes

I'm using this code to spawn in a row of five bricks on top of one another. The first row is perfect, in position and move properly. However, the rows that spawn with the performSelector action are not being put in properly. The positions of the rows that spawn in are off halfway off the screen and instead of spawning the amount of 5 bricks, it spawns 25 the second time and the third time it spawn 125 bricks. I've used all the actions and methods in this project before without any problems can someone please tell me what's going on here.

This is the only code I have in the scene other than initWithSize and they wouldn't cause any problems.

-(void) addBricks:(CGSize)size {
for (int i = 0; i < 5; i++) {
    //create brick sprite from image
    SKSpriteNode *brick = [SKSpriteNode spriteNodeWithImageNamed:@"brick"];
    //resize bricks
    brick.size = CGSizeMake(60, 30);
    //psoition bricks
    int xPos = size.height/7.5 * (i+.5);
    int yPos = 450;
    brick.position = CGPointMake(xPos, yPos);

    //add move action
    SKAction *wait = [SKAction waitForDuration:3];
    SKAction *move = [SKAction moveByX:0 y:-36.9 duration:1];
    SKAction *sequence = [SKAction sequence:@[wait, move]];
    SKAction *repeatMove = [SKAction repeatActionForever:sequence];

    //add action to spawn bricks
    SKAction *spawn = [SKAction performSelector:@selector(addBricks:) onTarget:(self)];
    SKAction *delay = [SKAction waitForDuration:6];
    SKAction *delayThenSpawn = [SKAction sequence:@[delay, spawn]];

    [self runAction:delayThenSpawn];
    [brick runAction:repeatMove];
    [self addChild:brick];

}
}

Any help would be greatly appreciated.

1
You can't performSelector with a selector that takes a parameter since you can't pass a parameter. Once the action calls the selector, the size parameter is undefined. If you're lucky it's 0,0 but if you're not, it contains garbage. Fortunately it seems you aren't using the parameter. Yet, it's not legal to performSelector with a mismatching signature. - LearnCocos2D
It's passing in the size parameter and the y position but not the x position. Maybe because it's not a single integer. Would defining the x position outside of the addBricks method help? @LearnCocos2D - Nicholas Whitley

1 Answers

0
votes

It makes sense that youre not seeing what you expect. you're recursively calling this method.

each time addbricks is called, you get five bricks. But addbricks is calling itself.. so 5 bricks x 5 bricks x 5 bricks and so on.

you have to rethink this. why are you spawning more bricks inside of addbricks?

I'm guessing the reason youre doing this is so you can spawn bricks continuously forever. but you can do this without recursion.

outside of your addBricks method, just do

[self runAction:[SKAction repeatActionForever:delayThenSpawn]]