首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HitTest for SKSpriteNode

HitTest for SKSpriteNode
EN

Stack Overflow用户
提问于 2017-01-11 15:31:42
回答 1查看 1.2K关注 0票数 5

这是我的问题:

我使用SpriteKit,当触摸事件发生在某个矩形中时,我想忽略它(防止调用touchesBegan)。我想这样做的方式类似于“凌驾于hitTestWithEvent of UIView”。但是,对于SKSpriteNode,我找不到任何类似的方法,可以忽略事件并阻止调用touchesBegan

好的

  • 我可以将isUserInteractionEnabled设置为false,但它禁用了整个精灵,而不仅仅是一个部分。
  • 我可以检查触摸在touchesBegan方法中的位置,但这是晚些时候-其他在同一位置下的精灵将不再接收此事件。
  • 我也尝试使用SKCropNode,但它只是防止显示精灵,甚至在不可见的区域也会处理事件。

有没有人知道如何防止部分精灵处理一个事件?

EN

回答 1

Stack Overflow用户

发布于 2017-01-11 18:11:18

open func nodes(at p: CGPoint) -> [SKNode]可用于检测您已触及某个点的节点。之后,您可以将每个节点的CGRect区域排除在外。

代码语言:javascript
复制
import SpriteKit
class GameScene: SKScene {
    var warningZone = CGRect(x: -80, y: -60, width: 100, height: 100)
    override func didMove(to view: SKView) {
        let nodeRed = SKSpriteNode.init(color: .red, size: CGSize(width:300,height:200))
        nodeRed.name = "nodeRed"
        addChild(nodeRed)
        nodeRed.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
        let nodeBlue = SKSpriteNode.init(color: .blue, size: CGSize(width:300,height:200))
        nodeBlue.name = "nodeBlue"
        addChild(nodeBlue)
        nodeBlue.position = CGPoint(x:self.frame.midX+100,y:self.frame.midY+20)
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            let nodesTouched = self.nodes(at: location)
            for node in nodesTouched {
                guard let n = node.name else { return }
                print("Node touched: \(node.name) at point:\(location)")
                switch n {
                case "nodeRed":
                    // do your exclusions for the nodeRed
                    print("\(node.frame)")
                    if !warningZone.contains(location) {
                        print("you have touch a safe red zone")
                    }
                case "nodeBlue":
                    // do your exclusions for the nodeBlue
                    print("\(node.frame)")
                default:
                    break
                }
            }
        }
    }
}

Output (我用白色矩形绘制了warningZone,但只显示了它在哪里.):

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41594805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档