user5480023
user5480023

Reputation:

Subclassed node, but want to detect touch in the scene

I have a subclassed node called LocationNode, where touch is enabled. It looks like this.

class LocationNode: SKSpriteNode, CustomNodeEvents {
func didMoveToScene() {
    self.isUserInteractionEnabled = true
}
}

I haven't overriden touchesBegan in this subclass file, because I want to control all touch events like this in the actual scene file:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchLocation = touches.first!.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    //if touchedNode.name != nil {
        print("touched")
    //}
}

When I try do this, however, it doesn't work. How can I control touch events for a subclassed node in the scene file?

EDIT:

Here's what my override function looks like in the scene.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchLocation = touches.first!.location(in: self)
    let touchedNode = self.atPoint(touchLocation)
    print("TOUCHED")
}

Upvotes: 2

Views: 81

Answers (1)

Alessandro Ornano
Alessandro Ornano

Reputation: 35392

You could implement this code below in your custom class, in this case LocationNode, to have a "return of touches" to the parent class, then you can handle the touches in both places (also to the main scene) :

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            print("touched!")
        }
        guard let parent = self.parent else { return }
        parent.touchesBegan(touches, with: event)
}

Upvotes: 2

Related Questions