Jorge Vega Sánchez
Jorge Vega Sánchez

Reputation: 7590

Check if SKAction contains an action (swift)

I'm trying to program a little game using swift. I'm translating some old obj-C sprite-kit code and doesn't find how to translate this code. In obj-C a SKACtion has a member called hasActions that tells you if the vars contains an action but in swift seems that theses property doesn't exists and also there isn't a method to do the same action.

Original obj-C code :

SKAction *animAction = [self.player actionForKey:animationKey];

    // If this animation is already running or there are no frames we exit
    if ( animAction || animationFrames.count < 1 )
    {
        return;
    }

Swift code

var animAction : SKAction = player.actionForKey(animationKey)!

// If this animation is already running or there are no frames we exit
if animAction || animationFrames.count < 1
{
    return
}

variable animationFrames.count is an array and doesn't throw any error. The exact error is 'Type 'SkAction doesn't conform to protocol BooleanType'

Thanks in advance.

Upvotes: 1

Views: 990

Answers (2)

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

Using Swift 2.x you can easily do:

public extension SKNode {
    public func actionForKeyIsRunning(key: String) -> Bool {
        return self.actionForKey(key) != nil ? true : false
    }
}

And you can write for example:

var myHero: SKSpriteNode!
...
if myHero.actionForKeyIsRunning("moveLeft") {
   // my character moving to the left
   print("moving to the left")
} 

Upvotes: 0

Mehdi.Sqalli
Mehdi.Sqalli

Reputation: 510

You need to write

var animAction : SKAction! = player.actionForKey(animationKey)

if animAction != nil || animationFrames.count < 1 {

return 

}

The error was on animAction, not animationFrames.

For the hasActions, it is still there in Swift

https://developer.apple.com/library/mac/documentation/SpriteKit/Reference/SKNode_Ref/index.html#//apple_ref/occ/instm/SKNode/hasActions

var node = SKNode()

node.hasActions()

Upvotes: 1

Related Questions