Reputation: 316
Im trying to create a sprite and give it a random y position, currently some of the sprites spawn out of view or are partly cut off. Which part do I have wrong(the screen is in landscape) and viewFrame is passed into the function and is the frame of the game scene
let enemyShip = SKSpriteNode(imageNamed: "enemyShip")
enemyShip.position = CGPointMake(viewFrame.maxX + enemyShip.size.height, CGFloat(arc4random_uniform(UInt32(viewFrame.maxY - enemyShip.size.height)) + UInt32(enemyShip.size.height)))
Upvotes: 1
Views: 80
Reputation: 8130
try this
func random(min min: CGFloat, max: CGFloat) -> CGFloat {
assert(min < max)
return CGFloat(Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min
}
let x = random(
min: enemyShip.size.width/2,
max: self.size.width - enemyShip.size.width/2
)
let y = random(
min: enemyShip.size.height/2,
max: self.size.height - enemyShip.size.height/2
)
enemyShip.position = CGPointMake(x, y)
Upvotes: 3