如何在 swift 中制作随机精灵位置生成器



我创建了一个游戏,鸟儿会随机出现在屏幕上。纵向模式。希望它们从随机 x 位置(从帧中间)出现我还希望它们位于屏幕的随机 Y 位置("自我"屏幕的最大顶部)

代码的顶行有效(随机生成器),但只在屏幕的一侧(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)

应该给出想要的结果。

最新更新