尝试在带有SpriteKit场景(SWIFT)的didMoveToView中使用waitForDuration延迟生成节点但不能正常工作

时间:2016-05-19 18:29:50

标签: ios swift sprite-kit skspritenode sklabelnode

我试图在游戏开始时阻止我的节点掉落一两秒钟。所以我的问题是,当我按下启动时,节点已经在屏幕的一半。我也尝试改变节点开始的高度,但这似乎是一个昂贵的解决方案,因为我要小心不要让我的FPS太低。在我的代码中,我试图在didMoveToView中执行此操作,并且我使用waitForDuration但它不起作用。

Example Image of Nodes Falling Down

任何SpriteKit大师都知道我应该做什么?我正在使用Swift。 这是我的代码:

    override func didMoveToView(view: SKView) {

            let wait = SKAction.waitForDuration(2.5)
            let run = SKAction.runBlock {
                self.spawnNumbers()
            }
            numContainer.runAction(SKAction.sequence([wait, run]))
    }

func spawnNumbers() {

        let minValue = self.size.width / 8
        let maxValue = self.size.width - 36

        let spawnPoint = CGFloat(arc4random_uniform(UInt32(maxValue - minValue)))
        let action = SKAction.moveToY(-300, duration: 2)

        numContainer = SKSpriteNode(imageNamed: "Circle")
        numContainer.name = "Circle"
        numContainer.size = CGSize(width: 72, height: 72)
        numContainer.anchorPoint = CGPointMake(0, 0)
        numContainer.position = CGPoint(x: spawnPoint, y: self.size.height)
        numContainer.runAction(SKAction.repeatActionForever(action))
        numContainer.zPosition = 2

        let numberLabel = SKLabelNode(fontNamed: "AvenirNext-Bold")
        numberLabel.text = "\(numToTouch)"
        numberLabel.name = "Label"
        numberLabel.zPosition = -1
        numberLabel.position = CGPointMake(CGRectGetMidX(numContainer.centerRect) + 36, CGRectGetMidY(numContainer.centerRect) + 36)
        numberLabel.horizontalAlignmentMode = .Center
        numberLabel.verticalAlignmentMode = .Center
        numberLabel.fontColor = UIColor.whiteColor()
        numberLabel.fontSize = 28

        addChild(numContainer)
        numContainer.addChild(numberLabel)
        numContainerArray.append(numContainer)
        numToTouch += 1
    }

1 个答案:

答案 0 :(得分:0)

我认为你必须将2.5秒施放到NSTimeInterval:

 let wait = SKAction.waitForDuration(NSTimeInterval(2.5))

您还可以尝试将操作放在场景的init函数中:

 override init (size: CGSize) {
     super.init(size: size)

     //your code from before
 }

此外,不确定它是否重要,但这是我通常做的,它的工作原理,

 let wait = SKAction.waitForDuration(NSTimeInterval(2.5))
 let action = SKAction.runBlock({() in self.spawnNumbers()})
 let actionThenWait = SKAction.sequence([wait, action])
 self.runAction(actionThenWait)