ios - 如何让 'removeFromParent()'多次工作?

标签 ios swift xcode removechild addchild

我在我的 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()
            }

        }

    }

我预计每当我触摸一个物体时它就会消失。但这只发生在一个对象上,并且它在第一个对象上工作得很好并且符合预期,但其他九个对象没有任何反应。

最佳答案

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

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)
        }
    }

}

注意:这不是执行此操作的最佳方式,尤其是从性能的角度来看,但足以让您理解这个想法。

关于ios - 如何让 'removeFromParent()'多次工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56839329/

相关文章:

ios - 在 XCode 6 beta 7 中从 Swift 在 iOS 中打印

swift - 如何在 Swift 3.0 中使用物理体

swift - SpriteKit : How do I remove objects once they leave the screen?

ios - 在没有子类化的情况下将触发的操作绑定(bind)到函数

ios - 无法删除 tableView 中的行

javascript - 使用 Xcode 远程构建到 Mac 上的 Cordova "Error mounting to image"和 "No devices found to debug"

ios - 如何在TableView单元格中显示URL图像而不会卡住?

ios - 为什么我的 iOS 应用程序无法从 Firebase 数据库读取?

ios - 如何让后退栏按钮项目显示在 iOS 的导航项目中?

ios - 如何在空数组中打印数据