Nicholas Whitley
Nicholas Whitley

Reputation: 81

random x position issue

I have a circle spawning every few seconds and I have five lanes that I want them to spawn into but I want it to go to a different one at random. The code I'm using works properly but it won't let me use my five x positions? I've tried multiple solutions but they won't work. I'm still new to objective c so any help would be appreciated. (Also the code below isn't my whole method obviously but it's the only part I need to show.)

#import "GameScene.h"

int xPos1;
int xPos2;
int xPos3;
int xPos4;
int xPos5;

@implementation GameScene

-(void) addBall:(CGSize) size{
xPos1 = 8.5;
xPos2 = 74;
xPos3 = 138;
xPos4 = 203;
xPos5 = 267.5;

CGRect box = CGRectMake( arc4random()  , self.frame.size.height,    //pos
                        45, 45);   //size
UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:box];

SKShapeNode *circle = [SKShapeNode node];
circle.path = circlePath.CGPath;
circle.fillColor = [SKColor colorWithRed:(243.0f/255) green:(134.0f/255) blue:(48.0f/255) alpha:1.0];
circle.strokeColor = nil;
circle.lineWidth = 3;

//add physics
circle.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:circle.frame.size.width/2];

//appy actions to move sprite
SKAction *wait = [SKAction waitForDuration:2];
SKAction *move = [SKAction moveToY:-self.size.height - 50 duration:2];
SKAction *remove = [SKAction removeFromParent];
SKAction *sequence = [SKAction sequence:@[wait, move, remove]];
SKAction *repeat = [SKAction repeatActionForever:sequence];

SKAction *spawn = [SKAction performSelector:@selector(addBall:) onTarget:self];
SKAction *delay = [SKAction waitForDuration:2.5];
SKAction *spawnThenDelay = [SKAction sequence:@[delay, spawn]];


[self runAction:spawnThenDelay];
[circle runAction:repeat];
[self addChild:circle];

}

Here are the different things I've tried using the x positions in arc4random:

CGRect box = CGRectMake( arc4random() %(xPos1, xPos2, xPos3, xPos4, xPos5)  , self.frame.size.height,    //pos
                        45, 45);

CGRect box = CGRectMake( arc4random(xPos1, xPos2, xPos3, xPos4, xPos5)  , self.frame.size.height,    //pos
                        45, 45);

I've also tried just putting the integers directly in there...

Upvotes: 0

Views: 53

Answers (1)

rakeshbs
rakeshbs

Reputation: 24572

Try by creating an array of X Positions and selecting from that using a random index.

CGFloat xPositions[5] = {8.5,74,138,203,267.5};

int randomIndex = arc4random() % 5;
int randomXPosition = xPositions[randomIndex]

CGRect box = CGRectMake(randomXPosition, self.frame.size.height, 45, 45);
UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:box];

Upvotes: 2

Related Questions