firat.temel
firat.temel

Reputation: 115

Is there any way to get touched node not as SKNode but my custom class derived from SKSpriteNode

I want to detect touches in the GameScene not in my custom class (I know if i set userInteractionEnabled=true in my class i can easily detect touched node). However I have more than one custom classes so i need to detect touches in GameScene. However,

let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)

Here nodeAtPoint returns SKNode however i need my custom class to do my actions. Thanks for any help

Upvotes: 0

Views: 153

Answers (1)

vacawama
vacawama

Reputation: 154731

Use a condtional cast (as?) combined with optional binding (if let):

let location = touch.locationInNode(self)
if let touchedNode = nodeAtPoint(location) as? MyCustomClass {
    // If we get here, touchedNode is type MyCustomClass
}

If you have multiple classes that need to be handled in different ways, you can use a switch statement like so:

switch nodeAtPoint(location) {
    case let node as MyCustomClass1:
        // handle node of type MyCustomClass1
    case let node as MyCustomClass2:
        // handle node of type MyCustomClass2
    case let node as MyCustomClass3:
        // handle node of type MyCustomClass3
    default:
        // Nothing to do here
        break
}

Upvotes: 3

Related Questions