Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect touch on child node of object in SpriteKit

I have a custom class that is an SKNode, which in turn has several SKSpriteNodes in it. Is there a way I can detect touches on these child SKSpriteNodes from my game scene?

I'm working in swift

like image 370
Kyle Goslan Avatar asked Oct 12 '14 19:10

Kyle Goslan


2 Answers

Examine Apple's SceneKitVehicle demo. Someone kindly ported it to Swift.

The code you want is in the GameView.swift file. In the GameView you'll see the touchesBegan override. Here's my version of it for Swift 2.1:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    guard let scene = self.overlaySKScene else {
        return
    }

    let touch = touches.first!
    let viewTouchLocation = touch.locationInView(self)
    let sceneTouchPoint = scene .convertPointFromView(viewTouchLocation)
    let touchedNode = scene.nodeAtPoint(sceneTouchPoint)

    if (touchedNode.name == "Play") {
        print("play")
    }
}

If it's not clear; the GameView is set as the app's view class by way of the Storyboard.

like image 134
Graham Perks Avatar answered Nov 19 '22 09:11

Graham Perks


override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

   let touch = touches.anyObject() as UITouch

   let touchLocation = touch.locationInNode(self)

    if([yourSprite containsPoint: touchLocation])
    {
         //sprite contains touch
    }
}

Source: http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners

like image 10
meisenman Avatar answered Nov 19 '22 08:11

meisenman