作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在我的 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/
我是一名优秀的程序员,十分优秀!