我正在尝试使用 SKSpriteNode
在 SpriteKit 中创建叠加层。但是,我希望触摸通过叠加层,所以我将 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)
}
}
我已经尝试子类化 SKSpriteNode
并手动将触摸事件委托(delegate)给适当的节点,但这会导致很多奇怪的行为。
任何帮助将不胜感激。谢谢!
最佳答案
阅读您找到的实际来源:
/**
Controls whether or not the node receives touch events
*/
open var isUserInteractionEnabled: Bool
但这是指触摸的内部节点方法。
默认 isUserInteractionEnabled
是false 那么触摸像你的叠加层这样的 child SKSpriteNode
默认情况下,是对主(或父)类处理的简单触摸(对象在这里,存在,但如果您不执行任何操作,您只需触摸它)
要通过触摸浏览叠加层,您可以在 GameScene
上实现如下代码. 还请记住不要将 -1 用作 zPosition
因为意味着它在您的场景下方。
P.S. :我添加了一个 name
给你的 Sprite 把它召回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)
}
}
}
}
}
}
}
关于ios - SKSpriteNode 在 isUserInteractionEnabled false 时不让触摸通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40416319/