快速 - 检测路径中的触摸

时间:2016-08-28 16:19:32

标签: swift core-graphics cgpath

我的场景中有一些等距的瓷砖。框架重叠,所以我使用等距瓷砖形状的路径,并检查触摸是否在内部。

我的问题是我检测到触摸,但只是沿着路径,而不是路径内。我的道路或使用方式一定有问题。

这是“touchesEnded”方法中的代码:

for actualTouch in touches
        {
            let SKnode = self.nodeAtPoint(actualTouch.locationInNode(self))
            let spriteNode = SKnode as! SKSpriteNode
            if spriteNode.name != nil{
                let tileSize = CGSizeMake(75, 38)
                let locationInNode = actualTouch.locationInNode(SKnode)

                let isometricPath = CGPathCreateMutable()
                CGPathMoveToPoint(isometricPath, nil, 0, -(tileSize.height / 2))
                CGPathAddLineToPoint(isometricPath, nil, (tileSize.width / 2), 0)
                CGPathAddLineToPoint(isometricPath, nil, 0, (tileSize.height / 2))
                CGPathAddLineToPoint(isometricPath, nil, -(tileSize.width / 2), 0)
                CGPathCloseSubpath(isometricPath)
                CGPathMoveToPoint(isometricPath, nil, 0, 0)
                let isometricPathRef = isometricPath as CGPathRef

                if CGPathContainsPoint(isometricPathRef, nil, locationInNode, true) == true
                {
                    print("touchedTile:\(spriteNode.name!)")
                    spriteNode.alpha = 1
                }

            }
        }
你可以帮我看看我的错误吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

解决方案是迭代所有触摸的节点而不是覆盖"触摸"

let nodes = self.nodesAtPoint(touch.locationInNode(self))
        for node in nodes
        {

            let spriteNode = node as! SKSpriteNode
            if spriteNode.name != nil{
                let tileSize = CGSizeMake(75, 38)
                let locationInNode = touch.locationInNode(node)

                let isometricPath = CGPathCreateMutable()
                CGPathMoveToPoint(isometricPath, nil, 0, -(tileSize.height / 2))
                CGPathAddLineToPoint(isometricPath, nil, (tileSize.width / 2), 0)
                CGPathAddLineToPoint(isometricPath, nil, 0, (tileSize.height / 2))
                CGPathAddLineToPoint(isometricPath, nil, -(tileSize.width / 2), 0)
                CGPathCloseSubpath(isometricPath)
                let isometricPathRef = isometricPath as CGPathRef

                print("element")
                if CGPathContainsPoint(isometricPathRef, nil, locationInNode, true) == true
                {
                    print("touchedTile:\(spriteNode.name!)")
                    spriteNode.alpha = 1
                }

            }
        }