Rick C
Rick C

Reputation: 29

How to Make a Random Sprite Position Generator in Swift

I have created a game where birds will appear randomly on the screen. Portrait mode. Want them to appear from a random x position (from the middle of the frame) I also want them to position at a random Y position of the screen (max top of "self" screen)

The top line of code works(randomGenerator), but only goes on one side of the screen (X Position). I cannot put a negative value into the X position because it will not allow.

I then was trying other things as you can see.

what am I doing wrong?

var randomGenerater = CGPoint(x:Int(arc4random()%180) ,y:Int(arc4random()%260))
var minXPosition = (CGRectGetMidX(self.frame) * CGFloat(Float(arc4random()) / Float(300)))
var RandomYPosition = (CGRectGetMidY(self.frame) * CGFloat(Float(arc4random()) / Float(UINT32_MAX)))
var trial = (CGRectGetMidY(self.frame) + CGFloat(Float(arc4random()) - Float(UINT32_MAX))) 
var randomGenerator2 = CGPointMake(minXPosition, trial)
 bird.position = randomGenerator2

Upvotes: 3

Views: 3134

Answers (1)

Martin R
Martin R

Reputation: 540125

Generally,

func randomInRange(lo: Int, hi : Int) -> Int {
    return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
}

gives a random integer in the range lo ... hi, so

// x coordinate between MinX (left) and MaxX (right):
let randomX = randomInRange(Int(CGRectGetMinX(self.frame)), Int(CGRectGetMaxX(self.frame)))
// y coordinate between MinY (top) and MidY (middle):
let randomY = randomInRange(Int(CGRectGetMinY(self.frame)), Int(CGRectGetMidY(self.frame)))
let randomPoint = CGPoint(x: randomX, y: randomY)

should give the wanted result.

Upvotes: 4

Related Questions