1

I have a game and I can't seem to get the node to randomly spawn on x position, it will randomly spawn but often will go off screen and the game is then useless and have to restart it:

func addEnemy () {
    //enemy
    let minValue = self.size.width / 8;
    let maxValue = self.size.width-20;
    let spawnPoint = UInt32(maxValue - minValue);

    Enemy = SKSpriteNode(imageNamed: "Enemy")
    Enemy.size = CGSize(width: 150, height: 200)

    Enemy.position = CGPoint(x: CGFloat(arc4random_uniform(spawnPoint)), y: self.size.height)
    self.addChild(Enemy)
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Tye Howatt
  • 105
  • 2
  • 9

1 Answers1

1
let min: CGFloat = 15.0
let max: CGFloat = 200.0
let randomCGFloatBetweenMinAndMax = CGFloat(rand())/CGFloat(RAND_MAX)*(max-min)+min

or if you prefer

let randomCGFloatBetweenMinAndMax2 = CGFloat(arc4random_uniform(UInt32(max-min)) + UInt32(min))
user3441734
  • 16,722
  • 2
  • 40
  • 59