Arrays 从数组spritekit swift中删除节点
我正在为iOS开发一款小游戏(spritekit/swift) 我的场景中有一个SKSpriteNode数组,定义如下:Arrays 从数组spritekit swift中删除节点,arrays,swift,skspritenode,removeclass,Arrays,Swift,Skspritenode,Removeclass,我正在为iOS开发一款小游戏(spritekit/swift) 我的场景中有一个SKSpriteNode数组,定义如下: var spritesTree = [SKSpriteNode]() spritesTree = spritesCollectionTree(count: numTrees) for sprite in spritesTree { addChild(sprite) } 然后我用一个函数填充数组,并将它们添加到场景中,如下所示: var sp
var spritesTree = [SKSpriteNode]()
spritesTree = spritesCollectionTree(count: numTrees)
for sprite in spritesTree {
addChild(sprite)
}
然后我用一个函数填充数组,并将它们添加到场景中,如下所示:
var spritesTree = [SKSpriteNode]()
spritesTree = spritesCollectionTree(count: numTrees)
for sprite in spritesTree {
addChild(sprite)
}
之后,根据情况,进程会向数组中添加更多的树。如果我知道索引,我知道如何从场景和数组中删除元素
spritesTree[i].removeFromParent()
spritesTree.removeAtIndex(i)
但我的问题是,当我不知道索引时,删除这个数组中的一个特殊节点。例如,当一个精灵被触摸时
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)
override func touchsbegined(touchs:Set,withEvent-event:UIEvent){
/*当触摸开始时调用*/
用于触摸输入(触摸设置为){
let location=touch.locationInNode(自)
let positionInScene=触摸位置InNode(自身)
让touchedNode=self.nodeAtPoint(positionInScene)
在这种情况下,如果我不知道索引,如何从我的SKSpriteNode数组spritesTree中删除touchedNode?我以前读过一些关于indexOf的内容来查找索引,但它不适用于我的SKSpriteNode数组。你能帮我吗
最好,您可以为每个SKSpriteNode创建一个名称:
spritesTree[index].name = String(index)
选中节点后,将名称转换为Int
let location = touch.locationInNode(self)
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)
var index = Int(touchedNode.name)
touchedNode.removeFromParent()
spritesTree.removeAtIndex(index)
您可以为每个SKSpriteNode创建一个名称:
spritesTree[index].name = String(index)
选中节点后,将名称转换为Int
let location = touch.locationInNode(self)
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)
var index = Int(touchedNode.name)
touchedNode.removeFromParent()
spritesTree.removeAtIndex(index)
感谢您的回答,但这并没有完全解决我的问题。假设我有以下与位置匹配的列表节点名称[“0”、“1”、“2”、“3”、“4”)。当我删除第一个名为“2”的项目时,一切正常,但如果我尝试删除名为“4”的索引,则会失败,因为这些项目已使用位置0->“0”重新组织,1->“1”,2->“3”,3->“4”,现在数组中没有“4”位置。您知道是否有任何函数从名称返回项目位置吗?在循环中删除后全部重命名。或者您可以尝试按如下方式在数组中查找节点:对于0中的索引…spritesTree.count{if touchedNode==spritesTree[index]{spritesTree.removeAtIndex(index)}}谢谢你的回答,但它并没有完全解决我的问题。假设我有以下列表节点名称[“0”、“1”、“2”、“3”、“4”]这与位置匹配。当我删除第一个名为“2”的项目时,一切都正常,但如果然后我尝试删除名为“4”的索引,则会失败,因为这些项目已用位置0->“0”、1->“1”、2->“3”、3->“4”重新组织,现在没有“4”数组中的位置。您知道是否有任何函数从名称返回项目位置吗?在循环中删除后重命名all。或者您可以尝试将节点按如下方式查找到数组中:对于0中的索引…spritesTree.count{if touchedNode==spritesTree[index]{spritesTree.removeAtIndex(index)}