gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:34:43 25 4
gpt4 key购买 nike

我在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com