2016-07-29 10 views
1

저는 Swift와 SpriteKit을 사용하고 있습니다. 여기SKShapeNode를 만질 때 정확하게 감지하는 방법은 무엇입니까?

enter image description here

이는 "삼각형"의 각각 SKShapenode입니다 :

나는 다음과 같은 상황이있다. 제 문제는 누군가 터치 된 삼각형이 화면에 닿았을 때를 감지하고 싶습니다. 나는 모든 삼각형의 히트 박스가 직사각형이기 때문에 어떤 함수가 실제로 만져 졌는지 알고 싶을 때 내 함수가 모든 히트 박스를 건네 준다고 가정합니다.

사각형 대신 모양과 완벽하게 일치하는 히트 박스가있는 방법이 있습니까? 이것은 그 일을하는 가장 쉬운 방법이 될 것입니다

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 
       } 
      } 
     } 
    } 
} 

답변

1

당신은 더 적절한하는 대신 nodesAtPointSKShapeNodeCGPathContainsPoint를 사용을 시도 할 수 있습니다 :

여기에 내 현재 코드입니다 .

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) 
{ 
    for touch in touches { 
     let location = touch.locationInNode(self) 
     if theSpriteNode.containsPoint(location) { 
      //Do Whatever  
     } 
    } 
} 
+0

정확하게 원했던 것입니다! 그리고 "triangle"이라는 이름의 모든 노드는 SKShapeNodes이고,'enumerateChildNodesWithName' 뒤에 추가 할 수 있습니다.'shapenode = node as let! SKHapeNode'를 제거하고, 'if node is SKShapeNode'를 제거하고'if p = (node ​​as! SKShapeNode) .path'를 제거하면'CGPathContainsPoint (shapenode.path, nil, touchPosition, false)'를 가질 수 있습니까? – Drakalex

+0

안전하지는 않지만 enumerateChildNodesWithName은 일반 SKNode와 작동합니다.), 사과 가이드를 살펴보십시오. https://developer.apple.com/reference/spritekit/sknode/1483024-enumeratechildnodeswithname –

0

:

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 
      } 
     } 
    } 
} 
+0

어떻게 삼각형을 찾아서 찾을 수 있습니까? 어느 것이 만져 졌는가? – Confused