Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建精灵,然后使用Swift by touch删除SpriteKit中的特定精灵?_Swift_Sprite Kit - Fatal编程技术网

如何创建精灵,然后使用Swift by touch删除SpriteKit中的特定精灵?

如何创建精灵,然后使用Swift by touch删除SpriteKit中的特定精灵?,swift,sprite-kit,Swift,Sprite Kit,我想创建一堆精灵,当我触摸它们时,一次移除一个。到目前为止,当我添加代码时,最后一个精灵被移除,而不是我触摸的精灵 var sprite = SKSpriteNode?() var touchLocation : CGPoint? for touch in touches { let location = touch.locationInNode(self) touchLocation = location

我想创建一堆精灵,当我触摸它们时,一次移除一个。到目前为止,当我添加代码时,最后一个精灵被移除,而不是我触摸的精灵

var sprite = SKSpriteNode?()
var touchLocation : CGPoint?


for touch in touches {

        let location = touch.locationInNode(self)                  
        touchLocation = location
        addASprite()        
    }
    removeSprite()

}

func addASprite(){
        sprite = SKSpriteNode(color: UIColor.orangeColor(), size: CGSize(width: 100, height: 100))

        sprite!.position = touchLocation!
        self.addChild(sprite!)

}

func removeSprite(){


        if ((sprite?.containsPoint(touchLocation!) != nil)){

            sprite?.removeFromParent()

        }

}

要删除接触的节点,请执行以下操作:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)
        touchedNode.removeFromParent()
    }
覆盖函数触摸开始(触摸:设置,withEvent事件:UIEvent?){
接触{
let location=touch.locationInNode(自)
让touchedNode=nodeAtPoint(位置)
touchedNode.removeFromParent()
}

我假设for loop是在touchsbegind内部定义的,而“sprite”变量是作为属性定义的(它不是在某个方法内部本地定义的)?如果是这样的话,那么所发生的事情就是您在一次又一次地创建sprite,而不是“sprite”变量将只保留对上一个创建的节点的引用。我不得不删除一些垃圾,而这些垃圾确实被删除了。