【问题标题】:How to create a sprites then remove a specific sprite in SpriteKit with Swift by touch?如何创建精灵然后通过触摸在 SpriteKit 中使用 Swift 删除特定精灵?
【发布时间】:2015-11-04 13:06:26
【问题描述】:

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

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

        }

}

【问题讨论】:

  • 我认为 for 循环是在 touchesBegan 中定义的,并且“sprite”变量被定义为一个属性(它不是在某个方法中本地定义的)?如果是这样的话,发生的事情是你一遍又一遍地创建精灵,但是“精灵”变量最终会通过只保留对创建的最后一个节点的引用而结束。
  • 我不得不删除一些垃圾,但确实被删除了。

标签: swift sprite-kit


【解决方案1】:

移除接触的节点:

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

    for touch in touches {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)
        touchedNode.removeFromParent()
    }

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多