我在这个 Sprite 中有一个菜单按钮 (skSpriteNode) 和一个小的播放图标
mainButton.addChild (playIcon)
mainButton.name = "xyz"
addchild (mainButton)
好吧,我给按钮起了个名字来检查是否有这个名字的 Sprite 被触摸。
当我触摸按钮内的子图标时,touchedNode.name 为 nil。我为图标子项设置了 isUserInteractionEnabled = false。我想将触摸传递给 parent 。我该怎么做。
for touch in touches {
let location = touch.location(in: self)
let touchedNode = self.atPoint(location)
if (touchedNode.name != nil) {
print ("node \(touchedNode.name!)")
} else {
continue
}
}
最佳答案
您必须在 SKSpriteNode
的子类中实现 touchesBegan
并设置其 isUserInteractionEnabled = true
,以便接受和处理触摸对于那个特定的节点(按钮)。
import SpriteKit
protocol ButtonDelegate:class {
func printButtonsName(name:String?)
}
class Button : SKSpriteNode{
weak var delegate:ButtonDelegate?
init(name:String){
super.init(texture: nil, color: .purple, size: CGSize(width: 250, height: 250))
self.name = name
self.isUserInteractionEnabled = true
let icon = SKSpriteNode(color: .white, size: CGSize(width:100, height:100))
addChild(icon)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
delegate?.printButtonsName(name: self.name)
}
}
class GameScene: SKScene, ButtonDelegate {
override func didMove(to view: SKView) {
let button = Button(name:"xyz")
button.delegate = self
button.position = CGPoint(x: frame.midX - 50.0, y: frame.midY)
addChild(button)
}
func printButtonsName(name: String?) {
if let buttonName = name {
print("Pressed button : \(buttonName) ")
}
}
}
现在,此按钮将吞下触摸并且图标 Sprite 将被忽略。
我刚刚修改了 one 中的代码我的答案是为了根据您的需求制作一个示例,但如果有兴趣,您可以在该链接中更详细地阅读整个内容。
关于sprite-kit - spritekit 使子节点不可触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45380428/