我创建了一个游戏,鸟类会随机出现在屏幕上。 人像模式。 希望它们从随机的 x 位置出现(从框架的中间) 我还希望它们位于屏幕的随机 Y 位置(“ self ”屏幕的最大顶部)
第一行代码有效(randomGenerator),但只在屏幕的一侧(X 位置)。 我不能将负值放入 X 位置,因为它不允许。
如您所见,我随后尝试了其他事情。
我做错了什么?
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
最佳答案
一般来说,
func randomInRange(lo: Int, hi : Int) -> Int {
return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
}
给出 lo ... hi
范围内的随机整数,所以
// 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)
应该给出想要的结果。
关于ios - 如何在 Swift 中制作随机 Sprite 位置生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27069320/