1
votes

I got an issue with the positioning code. I got 4 objects, lets call them Obj1 Obj2 Obj3 Obj4. I want them to spawn on the right side of the screen, moving to the left site of the screen, and than disappear. Obj 1 and Obj 2 are on the same y position, Obj 3 should be a little bit higher like + 40 y, and Obj 4 should be the only one with a mobile y position.

Obj 1 , 2 and 3 need to have a x gap between them, while Obj 4 can be random.

I can code every single outcome of it, for eg. =

 int Obj1x = 320;
 int Obj1y = 200;

 Obj1.position = CGPointMake(Obj1x, Obj1y);

 int Obj2x = 0;
 int Obj2y = 0;

 int r1 = arc4random() % 2; // produces random numbers between 0 and 1
 if(r1 == 0)
 Obj2x = Obj1x + 80;
 if(r1 == 1)
 Obj2x = Obj1x + 100;

 int r2 = arc4random() % 1;
 if(r2 == 0)
 Obj2y = Obj1y;


 Obj2.position = CGPointMake(Obj2x, Obj2y);

This way, it would take too much to write every outcome for it. Is there any other way to code it? Thank you very much.

1

1 Answers

1
votes

You don't really say whether you are using Swift or Objective-C. Easy enough in either language, but will give code in Swift.

// Where height is something like the self.frame.size.height being passed
func randomY(height: CGFloat) -> CGFloat {
    return CGFloat(arc4random()) % CGFloat(height / 3)
}

Another way you could do this is to determine a min and max Y and pass that to a function to return a random range between those values.

// Return a random range
func randomRange(#min: CGFloat, #max: CGFloat) -> CGFloat {
    assert(min < max)
    return CGFloat(arc4random()) / 0xFFFFFFFF * (max - min) + min
}

For the fixed positions and all that, the idea in your pseudo code basically works. For the two objects that need have some kind of fixed relationship, just set the second object as the first object's x and y position +/- the fixed amount.

Edit: Updated method. Previous example had a CGFloat Extension that was not included.