延迟for循环的迭代

时间:2018-05-16 05:20:11

标签: swift for-loop sprite-kit delay

我一直在努力解决这个问题。我有一个for循环,正在创建一组SKSpriteNodes并给它们物理等。这似乎导致在运行此循环时游戏中的延迟。我已经成功延迟了spriteNodes的实际添加,但这似乎没有帮助解决滞后问题。我希望能够让for循环运行一次,等待一段时间,然后运行下一次迭代。这可能吗?

func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

func createRoadImages() {
    for (index, roadImage) in imageArrays.enumerated() {
        print(imageArrays)
        let roadSprite = SKSpriteNode(imageNamed: roadImage)
        roadSprite.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        roadSprite.position = CGPoint(x: 0, y: CGFloat(screenCounter) * roadSprite.size.height)
        roadSprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.size.width, height: self.size.height))
        roadSprite.physicsBody?.friction = roadFriction
        roadSprite.physicsBody?.mass = backgroundMass
        roadSprite.physicsBody?.linearDamping = damping
        roadSprite.physicsBody?.categoryBitMask = PhysicsCategory.RoadImageCategory.rawValue
        roadSprite.physicsBody?.collisionBitMask = PhysicsCategory.NoCollisionsCategory.rawValue
        roadSprite.physicsBody?.contactTestBitMask = PhysicsCategory.BroomCategory.rawValue
        roadSprite.physicsBody?.affectedByGravity = false
        roadSprite.physicsBody?.isDynamic = true

        roadSprite.zPosition = 1
        roadSprite.name = "Road \(index)"

        delay(delayFor * Double(index)) {
            self.addChild(roadSprite)
            print("Sprite added \(index)")
        }
    }
}

0 个答案:

没有答案