使精灵出现在随机的y点

时间:2016-01-20 22:10:31

标签: ios swift sprite-kit

我试图创建一个精灵并给它一个随机的y位置,目前一些精灵产生于视野之外或被部分切断。哪个部分我有错(屏幕是横向的),viewFrame传递到函数中,是游戏场景的框架

 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)))

1 个答案:

答案 0 :(得分:3)

试试这个

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)