Tom
Tom

Reputation: 2418

Spawn Sprites Random Positions along x Axis - (Sprite Kit, IOS)

I have currently run into a problem.

What i am trying to achieve..

Spawn sprites randomly along different x axis and the same y axis but not have the sprites intersect.

Issue

Sprites are intersecting and in some cases spawning more then once one the same location.

Your suggestions are greatly received

what i am currently doing

    for (int spawn = 0; spawn < 10; spawn++) {
            SKSpriteNode *obstacle = [self createEnemyRed];
            obstacle.anchorPoint = CGPointMake(0.5, 0.5 );
            obstacle.position = CGPointMake(RandomFloatRange( 0, self.size.width),
                                            bg.size.height/2 );

            obstacle.name = @"obstacle";
            [bg addChild:obstacle];

        }

Upvotes: 4

Views: 757

Answers (1)

sangony
sangony

Reputation: 11696

Based on the little amount of code you have shown it is difficult to give you an answer which will fit your needs but consider using some of these suggestions.

  1. Add your randomly generating sprites into a NSMutableArray.

  2. Use the SKNode class command intersectsNode: to see if the current generated sprite intersects with any other currently active sprite. If yes, then try for another coordinate.

  3. If you want to only have unique coordinates and not repeat the same ones again, you need to store the coordinates in a second array and perform an additional check when generating your new sprite.

Upvotes: 3

Related Questions