【问题标题】:Swift 3 test if SKSpriteNode subclass of SKNode contains touchesSwift 3 测试 SKNode 的 SKSpriteNode 子类是否包含触摸
【发布时间】:2017-11-14 12:05:32
【问题描述】:
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

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

【问题讨论】:

  • 您使用了错误的方法,您想使用atPoint 获取某个节点并检查该节点是否为SubclassNode。另外我建议不要以大写字母开头变量,这会引起混淆。类型应该是大写的,而变量应该是小写的。
  • 你能给我举个例子吗?我也给子类起了一个名字,但它仍然不起作用。 (对不起,我通常使用小写的大写字母。这是一些经过编辑的代码,我并没有真正注意)

标签: ios swift sprite-kit touchesbegan


【解决方案1】:

我在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")
            }
        }
    }
}

【讨论】:

  • 这就是为什么我有时尽量不回答的原因,一点点研究就会有很长的路要走。你自学得越多,你在尝试解决问题时就会做得越好。
  • 感谢您的建议! ? 我会在下一次得出结论之前做更多的研究。
猜你喜欢
  • 2023-03-08
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多