swiftsprite-kitskspritenodesknodetouchesended

How to access objects of SKSpriteNode subclass when moving them (Swift)


I am confused with the objects of my class Card that is the subclass of SKSpriteNode. How do I get access to these objects when a user move them. So far I can only access SKNode objects overriding touchesEnded function.

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch : UITouch = touches.first as UITouch!
    let touchLocation = touch.locationInNode(self)
    touchedNode = self.nodeAtPoint(touchLocation)
    touchedNode.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
    touchedNode.zPosition = 0
}

I need to know what object the user is moving but in this case when touchedNode is an object of SKNode class (not my Card object class) I am not able to figure that out.


Solution

  • The is operator is exactly what you need.

    The is operator compares the types of the two operands. If they are of the same type, or one is a subclass of the other, the expression evaluates to true.

    So you can check it like this:

    if touchedNode is Card {
        // do stuff
    }
    

    Now what you might want to do is that if touchedNode is really a Card, I want to use the methods I defined in the Card class on the touchedNode.

    To do this, you need to cast the touchedObject to Card:

    let cardNode = touchedNode as! Card
    

    Then you can call your methods on cardNode!