0
votes

I am trying to make an iPhone game and I am trying to add random images in different position.

Here is what I want to do There is 6 different color oval nodes (enemy) When the game starts I want there to be 5 enemy nodes.

When the player node contacts enemy node, enemy node will disappear and then right away another enemy node will be added in different location.

But some times some nodes appear in same location so it looks like there is 4 nodes instead of 5. If there is a node already in a specific location how can I not add another node there but some other location?
Below I added a part of the code I wrote. It might be something very easy but I am new to programming and I could not figure that out.

Thank you,

-(void) addWaterBall { for (int i = 0; i < 5; i++) {

NSUInteger randomWaterBall = [Util randomWithMin:0 max:8];
WaterBall *waterBall = [WaterBall waterBallOfType:randomWaterBall];


float y = self.frame.size.height - ((((self.frame.size.height/2)-10)/10) * [Util randomWithMin:1 max:10]);
float x = (self.frame.size.width/10) * [Util randomWithMin:1 max:10];

 waterBall.position = CGPointMake(x, y);


 waterBall.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:waterBall.size.width/2];
 waterBall.physicsBody.dynamic = YES;
 waterBall.physicsBody.affectedByGravity = NO;



waterBall.physicsBody.categoryBitMask = waterBallCategory;
waterBall.physicsBody.contactTestBitMask = sharkCategory  ;
//waterBall.physicsBody.collisionBitMask = ;


        [self addChild:waterBall];

 }
}
2

2 Answers

0
votes

What I would do is stick in a [self enumerateChildNodesWithName…….] after generating the random co-ordinates and compare the random x and y co-ordinates with those on each enumerated node, if they are the same or too close then generate new random co-ordinates. This is probably best done in a while loop.

0
votes
-(void)addWaterBall
{
NSUInteger randomWaterBall = [Util randomWithMin:0 max:8];
WaterBall *waterBall = [WaterBall waterBallOfType:randomWaterBall];
waterBall.name = @"WaterBall";


    [self enumerateChildNodesWithName:@"WaterBall" usingBlock:^(SKNode *node, BOOL *stop) {


        float y = self.frame.size.height - ((((self.frame.size.height/2)-10)/10) * [Util randomWithMin:1 max:10]);
        float x = (self.frame.size.width/10) * [Util randomWithMin:1 max:10];

        node.position = CGPointMake(x, y);


        node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:waterBall.size.width/2];
        node.physicsBody.dynamic = YES;
        node.physicsBody.affectedByGravity = NO;



        node.physicsBody.categoryBitMask = waterBallCategory;
        node.physicsBody.contactTestBitMask = sharkCategory  ;
        //waterBall.physicsBody.collisionBitMask = ;


        [self addChild:waterBall];
    }];

}