【问题标题】:sprites are not removed - swift精灵不会被移除 - 快速
【发布时间】:2015-11-17 21:22:21
【问题描述】:

我正在尝试删除一些精灵,但并非所有精灵都被删除。请检查下面的代码。

    func removeSquare(squareSprite : SKNode)   {        

       for (index, value) in squares.enumerate()    {

           if Int(value.sprite.position.x) == Int(squareSprite.position.x)  {
              for i in 0..<2  {
                  if index - i >= 0  {
                    squares[index - i].sprite.removeFromParent()
                    squares.removeAtIndex(index - i)
                    print("index - i is \(index - i)")
                    print("squares.count is \(squares.count)")
                  }
              }
           }
       }

当i 大于零时,精灵不会被移除,否则当它为零时,它会移除精灵。 squares 是一个包含方形 sprite 的数组,这些 sprite 具有 sprite 类型的 SKSpriteNode 属性。我还检查了正方形的数量,并且数量适当减少了,但精灵仍在屏幕上。

【问题讨论】:

  • 您要删除哪些精灵然后?
  • 听起来正方形的索引会改变,因为你正在做squares.removeAtIndex(index - i),所以在下一个循环中,1 处的 i 变为 0,你想反方向 1..>=0 所以它不会改变。
  • @Knight0fDragon 谢谢,这真的很有帮助。我还使用了另一个变量来表示索引。它现在正在工作。

标签: ios swift sprite-kit


【解决方案1】:

问题是您在迭代数组时正在减少数组。尝试将此行注释掉,以检查您的算法是否在原则上有效并删除了正确的精灵:

squares.removeAtIndex(index - i)

如果是,请将算法更改为从数组末尾开始

【讨论】:

    【解决方案2】:

    听起来 squares 的索引会改变,因为您正在执行 squares.removeAtIndex(index - i),每次迭代都会使您的数组变小,因此在下一个循环中,1 的 i 变为 0,你想在相反的方向1..&gt;=0 使数组变小而不改变数组中对象的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-23
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      相关资源
      最近更新 更多