使用 SKAction 调用带参数的函数
Using an SKAction to call a function with parameters
我正在尝试通过采用 1 个输入参数的 SKAction 调用函数。
当我声明 SKAction 时,出现错误:“无法将类型 '()' 的值转换为预期的参数类型 '() -> Void'
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]))
}
我已经 3 个月没有使用 SpriteKit 了。但是像下面这样的东西应该可以工作。
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)
}
通常当您遇到该错误时,这仅意味着您需要将函数括在大括号内。所以:
self.run(SKAction.repeat(SKAction.sequence([SKAction.wait(forDuration: 1), SKAction.run( { self.decreaseHealth(by: 5.0) } )]), count: 10))
如果你把它分成多行,它会更容易被发现。
这是因为 decreaseHealth
是 ()
类型,但 { decreasHealth }
是 () -> ()
或 () -> Void
类型
(闭包在Swift中是函数类型,因此有参数/参数和returns)
我正在尝试通过采用 1 个输入参数的 SKAction 调用函数。
当我声明 SKAction 时,出现错误:“无法将类型 '()' 的值转换为预期的参数类型 '() -> Void'
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]))
}
我已经 3 个月没有使用 SpriteKit 了。但是像下面这样的东西应该可以工作。
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)
}
通常当您遇到该错误时,这仅意味着您需要将函数括在大括号内。所以:
self.run(SKAction.repeat(SKAction.sequence([SKAction.wait(forDuration: 1), SKAction.run( { self.decreaseHealth(by: 5.0) } )]), count: 10))
如果你把它分成多行,它会更容易被发现。
这是因为 decreaseHealth
是 ()
类型,但 { decreasHealth }
是 () -> ()
或 () -> Void
(闭包在Swift中是函数类型,因此有参数/参数和returns)