Layon Tavares
Layon Tavares

Reputation: 99

How to check which SKTexture a SKSpriteNode is running at the moment of a click

I'm animating an SKSpriteNode with an array of textures T. Once i click i need to set a different animation depending on the ACTUAL texture that is running (Ex: Animating with 0-5 textures, I click at the moment when texture2 is visible, i check WHICH texture is visible (texture2) then do animation correspondent (animation2).

Something like the name of the texture would do for checking, but i don't think there is such atribute.

I know that this comparison won't work, but here's an example of a similar walkthrough:

if(knightNode?.texture == SKTexture.init(imageNamed: "knightRunning01")){
                        knight?.removeActionForKey("walkAnimation")
                        knight?.runAction(SKAction.animateWithTextures(attackingFrames[0], timePerFrame: 0.4))
                        print("done")
    }else if(knightNode?.texture == SKTexture.init(imageNamed: "knightRunning02")){
                        knight?.removeActionForKey("walkAnimation")
                        knight?.runAction(SKAction.animateWithTextures(attackingFrames[1], timePerFrame: 0.4))
                        print("done2")
    }else{
                        print("hehe")
    }

Sorry for my english.

Upvotes: 2

Views: 225

Answers (1)

Whirlwind
Whirlwind

Reputation: 13665

Nope there is no public property called name on SKTexture. Also you can't add a stored property called id through extension (without some hacking). And you cannot subclass SKTexture in order to add a stored property in that new subclass. This is from docs:

Subclassing Notes

This class cannot be subclassed.

Never tried it though, but I can imagine how problematic this can be, if even possible (obviously not according to the docs).

So the solution... You can store all textures in an array and use it later to find out what is the index of current texture, like this:

import SpriteKit

class GameScene: SKScene{

    var textures:[SKTexture] = []
    var sprite:SKSpriteNode!

    override func didMoveToView(view: SKView) {

        let atlas = SKTextureAtlas(named: "yourAtlasName")

        for i in 0...9 { textures.append(atlas.textureNamed(String(i))) }

        sprite = SKSpriteNode(texture: textures[0])
        sprite.position = CGPoint(x: frame.midX, y: frame.midY)
        addChild(sprite)

        let animation = SKAction.animateWithTextures(textures, timePerFrame: 2)
        let loop = SKAction.repeatActionForever(animation)

        sprite.runAction(loop, withKey: "aKey")

    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if let currentTexture = sprite.texture {

            if let index = textures.indexOf(currentTexture) {
                print("Index \(index)")
            }
        }
    }
}

Probably there are some more ways to accomplish this.

Upvotes: 2

Related Questions