如何精确检测SKShapeNode被触碰的时间?

3

我正在使用Swift和SpriteKit。

我遇到了以下的情况:

enter image description here

在这里,每个“三角形”都是一个SKShapenode。 我的问题是,我想检测当有人触摸屏幕时哪个三角形被触摸。 我假设所有这些三角形的碰撞框都是矩形,因此我的函数返回所有被触摸的碰撞框,而我只想知道哪一个实际上被触摸。

是否有任何方法可以使碰撞框完全匹配形状而不是矩形?

以下是我的当前代码:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    let touch = touches.first
    let touchPosition = touch!.locationInNode(self)
    let touchedNodes = self.nodesAtPoint(touchPosition)

    print(touchedNodes) //this should return only one "triangle" named node

    for touchedNode in touchedNodes
    {
        if let name = touchedNode.name
        {
            if name == "triangle"
            {
                let triangle = touchedNode as! SKShapeNode
                // stuff here
            }
        }
    }
}
3个回答

2

您可以尝试使用CGPathContainsPointSKShapeNode而不是nodesAtPoint,这更加适合:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    let touch = touches.first
    let touchPosition = touch!.locationInNode(self)
    self.enumerateChildNodesWithName("triangle") { node, _ in
        // do something with node
        if node is SKShapeNode {
            if let p = (node as! SKShapeNode).path {
                if CGPathContainsPoint(p, nil, touchPosition, false) {
                    print("you have touched triangle: \(node.name)")
                    let triangle = node as! SKShapeNode
                    // stuff here
                }
            }
        }
    }
}

这正是我想要的!而且所有名为“triangle”的节点都是SKShapeNodes,我们可以在enumerateChildNodesWithName之后添加let shapenode = node as! SKShapeNode,并删除if node is SKShapeNodeif let p = (node as! SKShapeNode).path,只保留if CGPathContainsPoint(shapenode.path, nil, touchPosition, false)吗? - Drakalex
这不安全,enumerateChildNodesWithName与通用的SKNode一起工作;请查看苹果指南:https://developer.apple.com/reference/spritekit/sknode/1483024-enumeratechildnodeswithname - Alessandro Ornano

2
这是最简单的做法。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    for touch in touches {
        let location = touch.locationInNode(self)
        if theSpriteNode.containsPoint(location) {
             //Do Whatever    
        }
    }
}

这个程序是如何通过三角形来找到被触碰的那一个呢? - Confused

0

我使用Swift 4来完成这个任务的方法如下:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { 
     return 
    }
    let touchPosition = touch.location(in: self)
    let touchedNodes = nodes(at: touchPosition)
    for node in touchedNodes {
        if let mynode = node as? SKShapeNode, node.name == "triangle" {
            //stuff here
            mynode.fillColor = .orange //...
        }
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接