【问题标题】:How to Make a Random Sprite Position Generator in Swift如何在 Swift 中制作随机精灵位置生成器
【发布时间】:2014-11-21 19:59:44
【问题描述】:

我创建了一个游戏,小鸟会随机出现在屏幕上。 人像模式。 希望它们从随机的 x 位置(从帧的中间)出现 我还希望它们定位在屏幕的随机 Y 位置(“自我”屏幕的最大顶部)

第一行代码有效(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

【问题讨论】:

    标签: ios xcode swift random generator


    【解决方案1】:

    一般来说

    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)
    

    应该给出想要的结果。

    【讨论】:

    • 感谢您对这个 randomInRange 的提醒。你给我的问题出现了错误,因为 hi 和 lo 没有设置。我不太了解该算法是否相当公平,所以我无法通过它。但是感谢您的帮助:)
    • @RickC:对不起,我不明白。您必须在源文件的某处定义 randomInRange() 函数。然后let randomX = randomInRange(..., ...)调用给定值的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    相关资源
    最近更新 更多