【问题标题】:Randomizing Circles in Rhythm Game Swift 2在节奏游戏 Swift 2 中随机化圆圈
【发布时间】:2017-05-02 18:28:01
【问题描述】:

我有一个游戏,你可以在圆圈落入目标时单击它们,但现在我有它,所以它们都只是从左到右落下,依此类推。我希望它们以随机顺序落下,但我不知道如何。这是我的代码:

var alternator = 0
var flag:Bool = true
var fallTimer:NSTimer?

func fallCircleWrapper() {

    if (flag == true) {
        self.alternator += 1
    } else {
        self.alternator -= 1
    }

    if (self.alternator == 0) {
        flag = true
    } else if (self.alternator == 5) {
        flag = false
    }

    self.hitAreaArray[self.alternator].emitNote(self.texture!)

}

【问题讨论】:

    标签: swift sprite-kit swift2


    【解决方案1】:

    要获取随机数,请使用 arc4random 函数之一,因此在本例中

    let directionLeft = arc4random()%2 == 0
    

    其他备注:不需要比较标志是否为真。

    这个答案How does one generate a random number in Apple's Swift language? 告诉你更多关于随机数的信息。

    【讨论】:

    • 我是新手,还在学习,你能告诉我在我的代码中如何处理它吗?谢谢
    • 这会给你一个布尔标志,每次你调用它时都会有一个随机值。 50%的时候是真的,50%的时候是假的。这是通过计算一个随机整数并计算模 2 来实现的,因此对于每个偶数,directionLeft 为真,否则为假。
    【解决方案2】:
    // import GameplayKit for it's random generator capabilities
    import GameplayKit
    
    // this expression generates an array of NSNumbers where the values
    // are 0 to 4 - [0, 1, 2, 3, 4] but wrapped in NSNumbers 
    let circleIndexes = (0..<5).map { return NSNumber(value: $0) }
    
    // uses a function in GameplayKit to shuffle the indexes in
    // the circleIndexes array
    let randomIndexes = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: circleIndexes) as! [Int]
    
    func fallCircleWrapper() {
    
        if (flag == true) {
            self.alternator += 1
        } else {
            self.alternator -= 1
        }
    
        if (self.alternator == 0) {
            flag = true
        } else if (self.alternator == 5) {
            flag = false
        }
    
       // Now we select the circle to drop by choosing
       // the next item out of the list of randomized indexes
       self.hitAreaArray[randomIndexes[self.alternator]].emitNote(self.texture!)
    }
    

    【讨论】:

    • 虽然这可能有效,但您还没有解释它在做什么。许多新开发者不知道 .map 的作用,也从未使用过 GK。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2015-07-04
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多