2016-07-29 21 views
1

私はSwiftとSpriteKitを使っています。SKShapeNodeがタッチされたときの正確な検出方法は?

私は次のような状況があります。ここでは

enter image description here

を、 "三角形" のそれぞれがSKShapenodeです。 私の問題は、誰かが触れている三角形の画面に触れたときを検出したいということです。 私は私の機能は、私が唯一実際に触れられた1知りたいしながら、すべてのhitboxesに触れ、私を返すように、すべてのこれらの三角形のヒットボックスが長方形であることを前提としています。

は完全代わりに長方形の形状に合わせヒットボックスを持ってする方法はありますか?これはそれを行うための最も簡単な方法だろう

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'の後に追加できます。' let shapenode = node! SKShapeNode'、およびノー​​ドがSKShapeNode'とであれば、 '削除' P =(!SKShapeNodeとしてノード)ちょうど '場合CGPathContainsPoint(shapenode.path、nilに、偽touchPosition)'を持っている.path'をしましょうか? – Drakalex

+0

それはsafetlyではありません、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

関連する問題