【问题标题】:How to make 'removeFromParent()' work multiple times?如何使“removeFromParent()”多次工作?
【发布时间】:2019-11-12 07:49:46
【问题描述】:

我在 GameScene 中随机加载了多个 SpriteNode,但实际上是多次添加的同一个 SpriteNode。我在 touchesEnded 中有一个函数,一旦在与 SpriteNode 相同的位置释放触摸,它就会删除一个 SpriteNode。这仅适用于初始 SpriteNode(添加的第一个 SpriteNode),但不适用于所有其他 SpriteNode。

我试图将代码“if object.contains(location)”变成一个while循环,这样它就会一直重复。那也没用。

var object = SKSpriteNode()
var objectCount = 0


func spawnObject() {

        object = SKSpriteNode(imageNamed: "image")
        object.position = CGPoint(x: randomX, y: randomY)
        objectCount = objectCount + 1
        self.addChild(object)

}


while objectCount < 10 {

        spawnObject()

}


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        for t in touches {

            let location = t.location(in: self)

            if object.contains(location) {
                object.removeFromParent()
            }

        }

    }

我希望每当我触摸一个物体时它就会消失。但这只发生在一个对象上,它工作得非常好,与第一个对象的预期一样,但其他九个对象没有反应。

【问题讨论】:

  • 它实际上只适用于最后一个对象,但你当然不知道是哪一个。原因是您只保留对单个对象的引用,并在随后创建的每个对象中覆盖它。您将需要使用数组之类的东西来跟踪所有对象,然后检查数组中的每个对象以查看是否需要将其删除。
  • 感谢您的信息。你能想出什么方法来避免需要使用数组,因为我很难正确使用它们。
  • 假设您在 SKNode 中,那么您可以使用 touch.locationInNode(self) 获取当前坐标中的触摸位置,然后使用 self.nodesAtPoint(location) 获取该位置处所有节点的数组。当然,然后您将返回一个数组,这将获得所有子节点,而不仅仅是您使用spawnObject 添加的任何子节点。
  • 我知道我不会使用数组。您能否提供一些代码来展示如何使用我上面的代码实现数组?因为我不知道如何将其转换为数组或集合。

标签: ios swift xcode removechild addchild


【解决方案1】:

好的,这是使用数组跟踪生成的对象的基础知识,以便您可以检查它们:

var objectList: [SKSpriteNode] = [] // Create an empty array


func spawnObject() {

    let object = SKSpriteNode(imageNamed: "image")
    object.position = CGPoint(x: randomX, y: randomY)
    self.addChild(object)

    objectList.append(object) // Add this object to our object array

}

while objectList.count < 10 {

spawnObject()

}


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    for t in touches {

        let location = t.location(in: self)

        // Check all objects in the array
        for object in objectList {
            if object.contains(location) {
                object.removeFromParent()
            }
        }
        // Now remove those items from our array
        objectList.removeAll { (object) -> Bool in
            object.contains(location)
        }
    }

}

注意:这不是最好的方法,尤其是从性能的角度来看,但它足以让这个想法得到理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2014-11-04
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多