如果SKNode的SKSpriteNode子类包含触摸,则Swift 3测试

时间:2017-11-14 12:05:32

标签: ios swift sprite-kit touchesbegan

class MainNode:SKNode {
    class Box: SKSpriteNode {
        override init(texture: SKTexture?, color: UIColor, size: CGSize) {
            super.init(texture: SKTexture(imageNamed: "testIMG1"), color: UIColor.clear, size: CGSize(width: 50, height: 50))
        }
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    var subclassNode: SKSpriteNode!
    var box = Box()

    convenience init(size: CGSize) {
        self.init()

        box = Box()
        box.position.x = 0

        subclassNode = SKSpriteNode(color: UIColor.red, size: CGSize(width: 40, height: 40))
        subclassNode.position.x =  0
        subclassNode.zPosition = 6

        self.addChild(subclassNode)
    }
}

在我的班级MainNode我试图测试SKSpriteNode子类Box是否包含我的GameScene中的触摸

添加

for touch in touches {
    let location = touch.location(in: self)
    if MainNode.SubclassNode.contains(location) {
        print("Subclass contains touch")
    }
}

到我的GameScene课程或我的MainNode课程似乎根本不起作用,即使SubclassNode.isUserInteractionEnabled = true

如何确定触摸是否在我的子类中?

1 个答案:

答案 0 :(得分:0)

我从KnightOfDragon

获得了更多的研究和帮助

我设置self.isUserInteractionEnabled = true然后给我的subclassNode命名subclassNode.name = "SubclassNode"然后我将此代码添加到我的MainNode

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let touchedNode = self.atPoint(location)
        if let name = touchedNode.name
        {
            if name == "SubclassNode" {
                print("touched Subclass Node")
            }
        }
    }
}