sprite-kit - spritekit 使子节点不可触摸

标签 sprite-kit

我在这个 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/

相关文章:

ios - 纵向视差滚动 Sprite 套件

sprite-kit - 翻转的X缩放破坏了碰撞处理(SpriteKit 7.1)

ios - MKMapView 覆盖 SKSpriteNodes

ios - 用户触摸时如何更改 Sprite 颜色

swift - 如何在 SKScene 中的某些 SKSpriteNode 上制作朦胧/多云效果

swift - EXC_BREAKPOINT -- 由使用 swift spritekit 的碰撞检测引起

ios - 很简单——我无法在方法 B 中访问我在方法 A 中声明的对象

ios - 如何用SKKeyframeSequence绘制渐变 : as per Apple docs

swift - 在 SpriteKit 中的 TileMap 上连接 Physicsbodies

ios - SpriteKit - 多个对象的接触检测