在节奏游戏Swift中随机化圈子2

时间:2017-05-02 18:28:01

标签: swift sprite-kit swift2

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

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!)

}

2 个答案:

答案 0 :(得分:0)

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

dataSource

其他说法:没有必要将该标志与true进行比较。

此答案How does one generate a random number in Apple's Swift language?会告诉您有关随机数的更多信息。

答案 1 :(得分:-1)

// 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!)
}