Search code examples
swiftsprite-kitskspritenodesknode

Change texture of SKNode that is an SKSpriteNode


In a game I'm making I can get the node the user is touching with

var node = self.nodeAtPoint(positionInScene)

However, this gets me an SKNode (even if the node the user touches is an SKSpriteNode) and I cannot use node.texture to change its texture. How can I change that SKNode to an SKSpriteNode or change its texture? (Actions won't work here because I need to pause the scene and they won't work when the scene is paused).


Solution

  • Casting is what you are looking for.

    For instance:

    If you are sure that the casting will be successful and your SKNode() is actually a SKSpriteNode, you can do the following:

    let s = SKNode()
    let ss: SKSpriteNode = (s as? SKSpriteNode)!
    

    However, it is always better to use the optional specially in casting:

    let ss2: SKSpriteNode? = s as? SKSpriteNode