2015-04-03 88 views
0

我有以下函數,它產生正方形並將它們添加到正方形數組。這會無限地添加新的正方形,直到函數停止。正方形陣列在SKScene中聲明如下:var rsArray = [RedSquare]()檢測在陣列中的SKNode觸摸

func spawnRedSquares() { 
    if !self.gameOver { 
     let rs = RedSquare() 
     var rsSpawnRange = self.frame.size.width/2 
     rs.position = CGPointMake(rsSpawnRange, CGRectGetMaxY(self.frame) + rs.sprite.size.height * 2) 
     rs.zPosition = 3 
     self.addChild(rs) 
     self.rsArray.append(rs) 

     let spawn = SKAction.runBlock(self.spawnRedSquares) 
     let delay = SKAction.waitForDuration(NSTimeInterval(timeBetweenRedSquares)) 
     let spawnThenDelay = SKAction.sequence([delay, spawn]) 
     self.runAction(spawnThenDelay) 
    } 
} 

我試圖使用touchesBegan()功能,當陣列中的特定正方形被分接,以檢測並然後訪問方的屬性。我無法弄清楚如何確定哪個廣場被觸摸。我會如何去做這件事?

回答

0

我能夠通過試驗來回答我自己的問題,並決定如果其他人有類似的問題,我會發布答案。我在touchesBegan()函數中需要的代碼如下:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 
    for touch: AnyObject in touches { 
     let location = touch.locationInNode(self) 
     let rsCurrent = self.nodeAtPoint(location) 
     for RedSquare in rsArray { 
      let rsBody = RedSquare.sprite.physicsBody 
       if rsBody == rsCurrent.physicsBody? { 
        //Action when RedSquare is touched 
      } 
     } 
    } 
} 
0

給你產生一個獨特名稱的每個正方形,並在touchesBegan中檢查該名稱。您可以使用一個計數器,做

rs.name = "square\(counter++)" 

在的touchesBegan可以檢索觸摸節點的名稱,並檢查它針對陣列中的節點的名稱。

0

首先你必須給rs node一個名字。例如

rs.name = "RedSquare" 

然後你可以使用nodeAtPoint函數來找到特定觸摸點的節點。如果該節點是RedSquare,則可以對其進行修改。

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { 
    for touch in touches { 

     let touchPoint = touch.locationInNode(self) 
     let node = self.nodeAtPoint(touchPoint) 

     if node.name == "RedSquare" { 
      // Modify node 
     } 

    } 
} 
+0

出於某種原因,我似乎無法得到此工作。我嘗試在'spawnRedSquares'函數或'RedSquare'類中添加名稱'RedSquare'',但無論哪種方式,當輕敲發生時都不會發生。 – 2015-04-04 05:00:03