【问题标题】:SKShapeNode seems to be missing touchesSKShapeNode 似乎缺少触摸
【发布时间】:2026-02-23 02:35:01
【问题描述】:

我想知道是否有好心的专家可以帮助我解决初学者的问题。我想使用 SKShapeNodes 来表示非矩形形状,但需要检测对它们的触摸。

我下面的代码似乎不起作用。我错过了一些琐碎的事情吗?

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!!
            }
        }
    }
}

【问题讨论】:

  • 这比我想象的还要离奇。使用相同的代码但使用三角形路径创建三角形不会出现此问题。所以 SpriteKit 对待圆形和三角形 SKShapeNodes 的方式肯定有根本的区别!

标签: ios skshapenode


【解决方案1】:

删除以下代码行:-

ball.isUserInteractionEnabled = true 

对我来说效果很好。

【讨论】: