以编程方式添加的 SpritekitNode 不会触发 touchesBegan,而通过场景编辑器添加的相同 spritekitNode 可以工作

SpritekitNode added programmatically does not trigger the touchesBegan while the same spritekitnode added through scene editor works

我以编程方式向场景添加了一个 SKSpriteNode(name=building1),它没有触发 touchesBegan 函数。所以我尝试通过场景编辑器(使用相同的纹理)添加一个精灵节点(name=building2,parent = GameScene)并且效果很好。我可以看到这两座建筑,但只有第二座触发了 touchesBegan 功能。

class GameScene: SKScene {    
var build = SKSpriteNode()

override func didMove(to view: SKView) {

    build = SKSpriteNode(imageNamed: "build")
    build.name = "building1"
    build.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    build.position = CGPoint(x: 0, y: 0)
    build.zPosition = 0
    build.isUserInteractionEnabled = true
    self.addChild(build)

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("Something was touched")
    for touch in touches {
        let location = touch.location(in: self)

        if atPoint(location).name! == "building1" {
            print("\(atPoint(location).name!) was touched")
        }
        if atPoint(location).name! == "building2" {
            print("\(atPoint(location).name!) was touched")
        }
    }

}


}

奇怪的是,当我触摸 building2(通过场景编辑器添加)时,我得到了输出 "Something was touched" "building2 was touched" 而 building1 甚至没有触发该功能,即没有显示任何内容日志。 我究竟做错了什么? 谢谢

删除这一行,它应该可以工作:

build.isUserInteractionEnabled = true

一开始可能看起来很奇怪。重点是让用户与节点交互,我为什么要禁用用户交互?

好吧,这就是文档对 isUserInteractionEnabled 的描述:

A Boolean value that indicates whether the node receives touch events.

所以如果我们将它设置为true,节点而不是场景将接收触摸事件。因此,场景的touchesBegan方法没有被调用。相反,节点的 touchesBegan 被调用。但是,如果我们将其设置为 false,节点将不会接收任何触摸事件。那么触摸事件去哪儿了呢?到节点的父节点(在本例中为场景)!

您从编辑器添加的节点默认有isUserInteractionEnabled = false