ios - 如何在 Swift 中制作随机 Sprite 位置生成器

标签 ios xcode swift random generator

我创建了一个游戏,鸟类会随机出现在屏幕上。 人像模式。 希望它们从随机的 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/

相关文章:

swift - 在 Swift 中断言通知对象和托管对象上下文相等

ios - 长按和短按 UIBUTTON

ios - 如何保存应用于 UIView 的 CATransform3D

ios - 如何在 IOS 中重新加载 UIBarButtonItem

特定类的 Swift 协议(protocol)

json - 如何轻松查看符合 `Codable` 协议(protocol)的对象的 JSON 输出

ios - 按位非运算符 (~) 不适用于 SWIFT 1.2 中的 bool 值

ios - 屏幕方向更改后页面右侧的空白区域

xcode - 为什么Xcode会创建无尽的文件夹递归?

xcode - IOS 自动布局动态前导和尾随约束