how to randomly spawn enemies on screen

let randomNumber = arc4random_uniform(2)

let x: CGFloat = randomNumber == 0 ? 1 : -1

enemy.position = CGPoint(x: (CGFloat(arc4random_uniform(UInt32(UIScreen.main.bounds.width))) * x), y: UIScreen.main.bounds.height)

here is my code for enemy spawn, it works but some of my enemies are spawning outside of my screen. What can i change to make them all spawn inside the border

So:

  • x is 1 or -1
  • enemy.position.y is always the screen height

You then want to generate a random point across the screen, for enemy.position.x...

  • You generate a random number
  • Then multiply it by x (which can be 1 or -1)

Isn't that going to generate a lot of negative x co-ordinates?!

To generate a random position across the screen width, try something like:

let enemyX = CGFloat.random(in: 0..<UIScreen.main.bounds.width)
how to randomly spawn enemies on screen
 
 
Q