使用SKAction调用带参数的函数

时间:2017-07-30 20:49:21

标签: swift sprite-kit skaction

我试图通过一个带有1个输入参数的SKAction调用一个函数。

当我宣布SKAction时,我收到错误:"无法转换类型'()'预期参数类型'() - >空隙'

self.run(SKAction.repeat(SKAction.sequence([SKAction.wait(forDuration: 1), SKAction.run(self.decreaseHealth(by: 5.0))]), count: 10))

func decreaseHealth(by amount: Double){
    print(health)
    health -= amount
    print(health)
    let percentageToDecrease = amount / totalHealth
    let resizeAction = SKAction.resize(toHeight: CGFloat(600*(1-percentageToDecrease)), duration: 1)
    let redAmount: CGFloat = CGFloat(1.0 - health / totalHealth)
    let greenAmount: CGFloat = CGFloat(health / totalHealth)
    let recolorAction = SKAction.colorize(with: UIColor(red: redAmount, green: greenAmount, blue: CGFloat(0.0), alpha: CGFloat(1.0)), colorBlendFactor: 0, duration: 1)

    healthBar.run(SKAction.group([resizeAction, recolorAction]))

}

2 个答案:

答案 0 :(得分:3)

通常当你得到那个错误时,它只是意味着你需要将函数括在花括号内。所以:

self.run(SKAction.repeat(SKAction.sequence([SKAction.wait(forDuration: 1), SKAction.run( { self.decreaseHealth(by: 5.0) } )]), count: 10))

如果你把它分成多行,那就更容易发现了。

这是因为decreaseHealth类型为(){ decreasHealth }类型为() -> ()() -> Void

(闭包是Swift中的函数类型,因此有参数/参数并返回)

答案 1 :(得分:2)

我还没有使用SpriteKit 3个月。但是类似下面的内容应该可行。

func repeatMe() {
    let waitAction = SKAction.wait(forDuration: 1.0)
    let completionAction = SKAction.run {
        self.decreaseHealth(by: 5.0)
    }
    let seqAction = SKAction.sequence([waitAction, completionAction])
    let repeatAction = SKAction.repeat(seqAction, count: 10)
}