gpt4 book ai didi

arrays - 按顺序循环遍历方 block

转载 作者:行者123 更新时间:2023-11-30 14:04:35 25 4
gpt4 key购买 nike

我有一个正方形网格,如下所示,我试图弄清楚如何循环遍历每一行(从下到上或反之亦然),选择一个随机正方形并模拟按下(按比例缩小然后放大) 。我使用以下代码将每一行创建为 5 个 SKShapeNode 的数组:

一排正方形:

//Row Seven
for var i = -2; i < 3; i++ {

firstSquare = SKShapeNode(rectOfSize: CGSize(width: self.view!.frame.size.width * (1/5), height: self.view!.frame.size.width * (1/5)))
firstSquare.fillColor = SKColor(hue: 225.0/360.0, saturation: 0.1176, brightness: 0.2667, alpha: 1.0)
firstSquare.strokeColor = SKColor.clearColor()
firstSquare.position = CGPoint(
x: CGRectGetMidX(self.frame) + ((firstSquare.frame.size.width + CGFloat(2)) * CGFloat(i)),
y: (CGRectGetMidY(self.frame) + self.frame.size.height / 4) - (firstSquare.frame.size.width + CGFloat(2)) * CGFloat(6))
rowSeven.append(firstSquare)
addChild(firstSquare)

}

七行中的每一行都添加到保存所有行的数组 (gameLayers) 中。

gameLayers = [rowOne, rowTwo, rowThree, rowFour, rowFive, rowSix, rowSeven]

我有以下代码来循环遍历 gameLayers 数组并选择每一行,选择一个随机元素并运行按下的动画。

private func randomIntergerInRange(low:Int, high: Int) -> Int {
let randomGeneratedNumber = low + Int(arc4random()) % (high - low);
return Int(randomGeneratedNumber)
}

func loopThrough() {

for eachRow in gameLayers {

let selectedSquare = eachRow[randomIntergerInRange(0, high: eachRow.count)]

let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(2) * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {

let scaleDown = SKAction.scaleTo(0.85, duration: 0.3)
let scaleUp = SKAction.scaleTo(1.0, duration: 0.3)
let scalingSequence = SKAction.sequence([scaleDown, scaleUp])

selectedSquare.runAction(scalingSequence)

}
}

}

在尝试此操作时,每行都会选择一个方 block ,但所有选定的方 block 都会同时运行动画,而不是像我希望的那样按顺序运行。

任何想法可能是什么原因。我认为 for 循环会按顺序运行每个元素的动画。

enter image description here

最佳答案

我认为这个问题可以通过递归循环来使用。在一行的正方形上运行动画后,调用相同的函数并更新该行以触发动画。

var selectedRowIndex = 0

func loopThrough() {
let rowSelected = gameLayers[selectedRowIndex] //Select a row from the gameLayers


let selectedNumber = self.randomIntergerInRange(0, high: rowSelected.count)
let squareSelected = rowSelected[selectedNumber] //Select a square from the selected Row.

//Run the animation on that square
let scaleDown = SKAction.scaleTo(0.9, duration: 0.2)
let scaleUp = SKAction.scaleTo(1.0, duration: 0.2)
let scalingSequence = SKAction.sequence([scaleDown,
scaleUp])

squareSelected.runAction(scalingSequence)


let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(1.3) * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {

//Delay for 1.3 seconds and call the function again. Increase the index of the selected row to select the next
if self.selectedRowIndex != self.gameLayers.count - 1 {
self.selectedRowIndex++
self. loopThrough()
}
}
}

关于arrays - 按顺序循环遍历方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32571536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com