使用全局函数永远重复动作

时间:2016-01-08 18:13:23

标签: swift sprite-kit repeat skaction

我有一个需要不断向上移动的矩形,但也是全局声明的,所以我可以在多个地方调用它:

   var obstacle = SKNode!

  override func didMoveToView {
     obstacle = rectangle()
    }


  func rectangle() -> SKNode {
   let rect = SKSpriteNode(imageNamed: "Rectangle@x2")
    rect.size = CGSizeMake(30, 30)

    rect.position = CGPointMake(210, -250)
    rect.physicsBody?.categoryBitMask = PhysicsCatagory.littleRect
   rect.physicsBody?.contactTestBitMask = PhysicsCatagory.bigRect
    rect.physicsBody?.collisionBitMask = 0
   rect.physicsBody = SKPhysicsBody(rectangleOfSize: rect.size)
    rect.physicsBody?.dynamic = true
    rect.physicsBody?.affectedByGravity = false
    rect.runAction(
        SKAction.moveByX(0, y: 1200,
            duration: NSTimeInterval(6.5)))

    addChild(rect)
    return rect

}
When I attempt to run it as an action repeating forever like so, i get the error "cannot convert value of type SKNode to argument runBlock" : 

   runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(rectangle),
            SKAction.waitForDuration(4.0)])))

那么有没有办法为这样设置的函数声明这种动作?先感谢您。

1 个答案:

答案 0 :(得分:1)

首先,这个var obstacle = SKNode!会产生错误。您应该声明一个隐式解包的可选项,如下所示:

 var obstacle:SKNode! 

关于主要问题(不分析代码实际执行的逻辑,)...您正在将SKNode类的实例传递给+runBlock:方法(接受闭包),因此错误。要解决这个问题,你必须传递一个闭包,如下所示:

override func didMoveToView(view: SKView) {

    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock({[unowned self] in self.rectangle()}),
            SKAction.waitForDuration(4.0)])))
}