Dan O'Leary
Dan O'Leary

Reputation: 97

Using an SKAction to call a function with parameters

I am trying to call a function via an SKAction that takes 1 input parameter.

When I declare the SKAction, I get an error: "Cannot convert value of type '()' to expected argument type '() -> 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]))

}

Upvotes: 2

Views: 555

Answers (2)

Fluidity
Fluidity

Reputation: 3995

usually when you get that error, it just means you need to enclose the function inside of curly brackets. so:

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

If you had split this into multiple lines, it would have been easier to spot.

this is because decreaseHealth is of type () but { decreasHealth } if of type () -> () or () -> Void

(Closures are function type in Swift, thus have parameter / arguments and returns)

Upvotes: 4

El Tomato
El Tomato

Reputation: 6707

I haven't used SpriteKit for 3 months. But something like the following should work.

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)
}

Upvotes: 2

Related Questions