【问题标题】:Detect Touches on SKNode in Array检测数组中 SKNode 上的触摸
【发布时间】:2015-04-03 07:14:18
【问题描述】:

我有以下函数生成正方形并将它们添加到正方形数组中。这会无限期地添加新的方块,直到函数停止。正方形数组在SKScene 中声明,如下所示:var rsArray = [RedSquare]()

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() 函数来检测何时点击数组中的特定方块,然后访问该方块的属性。我无法弄清楚如何确定正在触摸哪个方块。我该怎么做呢?

【问题讨论】:

    标签: ios sprite-kit touches sknode


    【解决方案1】:

    为您生成的每个方块指定一个唯一名称,并在 touchesBegan 中检查该名称。您可以使用计数器并做

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

    在 touchesBegan 中,您可以检索被触摸节点的名称,并将其与数组中的节点名称进行检查。

    【讨论】:

      【解决方案2】:

      首先你必须给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
              }
      
          }
      }
      

      【讨论】:

      • 出于某种原因,我似乎无法让它工作。我尝试在spawnRedSquares 函数或RedSquare 类中添加名称"RedSquare",但无论哪种方式,当点击发生时都不会发生任何事情。
      【解决方案3】:

      我能够通过实验回答我自己的问题,并决定发布答案以防其他人遇到类似问题。我在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
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多