当isUserInteractionEnabled为false时,SKSpriteNode不允许触摸通过

Zoy*_*oyt 2 touch ios sprite-kit swift

我正在尝试使用一个在SpriteKit中创建一个叠加层SKSpriteNode.但是,我希望触摸通过叠加层,所以我设置isUserInteractionEnabled为false.但是,当我这样做时,SKSpriteNode仍然似乎吸收了所有的触摸,并且不允许底层节点做任何事情.

这是我正在谈论的一个例子:

class 

TouchableSprite: SKShapeNode {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("Touch began")
    }
}

class GameScene: SKScene {
    override func sceneDidLoad() {
        // Creat touchable
        let touchable = TouchableSprite(circleOfRadius: 100)
        touchable.zPosition = -1
        touchable.fillColor = SKColor.red
        touchable.isUserInteractionEnabled = true
        addChild(touchable)


        // Create overlay
        let overlayNode = SKSpriteNode(imageNamed: "Fade")
        overlayNode.zPosition = 1
        overlayNode.isUserInteractionEnabled = false
        addChild(overlayNode)
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了子类化SKSpriteNode并手动将触摸事件委托给适当的节点,但这会导致很多奇怪的行为.

任何帮助将非常感激.谢谢!

Ale*_*ano 6

阅读您找到的实际来源:

/**
  Controls whether or not the node receives touch events
*/
open var isUserInteractionEnabled: Bool
Run Code Online (Sandbox Code Playgroud)

但这是指内部节点的触摸方法.默认情况下isUserInteractionEnabledfalse,那么SKSpriteNode默认情况下,像你的叠加层一样对孩子进行触摸是对主(或父)类处理的简单触摸(对象在这里,存在但是如果你没有实现任何动作,你只需触摸它)

要通过触摸浏览覆盖图,您可以将以下代码实现到GameScene.Remember也不使用-1,zPosition因为它意味着它位于您的场景下方.

PS:我已经name为你的精灵添加了一个回忆它,touchesBegan但你可以创建全局变量GameScene:

override func sceneDidLoad() {
        // Creat touchable
        let touchable = TouchableSprite(circleOfRadius: 100)
        touchable.zPosition = 0
        touchable.fillColor = SKColor.red
        touchable.isUserInteractionEnabled = true
        touchable.name = "touchable"
        addChild(touchable)
        // Create overlay
        let overlayNode = SKSpriteNode(imageNamed: "fade")
        overlayNode.zPosition = 1
        overlayNode.name = "overlayNode"
        overlayNode.isUserInteractionEnabled = false
        addChild(overlayNode)
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("GameScene Touch began")
        for t in touches {
            let touchLocation = t.location(in: self)
            if let overlay = self.childNode(withName: "//overlayNode") as? SKSpriteNode {
                if overlay.contains(touchLocation) {
                    print("overlay touched")
                    if let touchable = self.childNode(withName: "//touchable") as? TouchableSprite {
                        if touchable.contains(touchLocation) {
                            touchable.touchesBegan(touches, with: event)
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)