Search code examples
iosskshapenode

SKShapeNode seems to be missing touches


I wonder if some kind expert could help me out with a beginner's problem. I want to use SKShapeNodes to represent non-rectangular shapes but need to detect touches on them.

The code I have below does not seem to work. Am I missing something trivial?

import SpriteKit

class GameScene: SKScene , SKPhysicsContactDelegate {

    var ball: SKShapeNode!

    override func didMove(to view: SKView) {
        backgroundColor = .white
        ball = createBall()
        ball.position = CGPoint.zero
        addChild(ball)
    }

    func createBall() -> SKShapeNode {

        let path = CGMutablePath()
        path.addArc(center: CGPoint.zero,
                    radius: 35,
                    startAngle: 0,
                    endAngle: CGFloat.pi * 2,
                    clockwise: true)
        let ball = SKShapeNode(path: path,  centered: true)
        ball.lineWidth = 1
        ball.fillColor = .lightGray
        ball.strokeColor = .black
        ball.isUserInteractionEnabled = true
        return ball
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            print("\(location)")   // diagnostic - produces output whenever click is NOT within SKShapeNode

            if ball.contains(location) {
                print("\(location)") // diagnostic - never produces output!!
            }
        }
    }
}

Solution

  • Remove the following line of code:-

    ball.isUserInteractionEnabled = true 
    

    It's Working fine For Me.