ios - 触摸时删除 SKSpriteNode

标签 ios swift sprite-kit skspritenode

我试图在点击 SKSpriteNodes 时删除它们,但是,我无法获取要删除的节点,只能获取最新创建的节点。而且因为节点每秒都会产生,所以当我点击一个节点时,它会删除下一个节点。这是我的代码:

class GameScene: SKScene {

var weapon = SKSpriteNode()
var badGuy = SKSpriteNode()

override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    spawnBadGuy()
    let spawn = SKAction.runBlock(spawnBadGuy)
    let wait = SKAction.waitForDuration(1)

    let sequence = SKAction.sequence([spawn, wait])
    runAction(SKAction.repeatActionForever(sequence))


}
func spawnBadGuy(){
    badGuy.name = "badguy"
    badGuy = SKSpriteNode(imageNamed: "redBall")
    badGuy.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    badGuy.setScale(0)
    let scaleUp = SKAction.scaleTo(0.15, duration: 2)

    let moveToSide = SKAction.moveTo(CGPoint(x: CGFloat.random(min: 0 + 50, max: self.size.width - 50 ), y: CGFloat.random(min: 0 + 50, max: self.size.height - 50 )), duration: 2)
    badGuy.runAction(moveToSide)
    badGuy.runAction(scaleUp)


    self.addChild(badGuy)

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */

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


        if touchedNode.name == "badguy"{

            badGuy.removeFromParent()

        }

我在两个完全不同的项目中遇到了同样的问题,一直未能找到解决方案。非常感谢任何帮助!

最佳答案

因为你写的是同一个变量。尝试:

func spawnBadGuy(){

    let localBadGuy = SKSpriteNode(imageNamed: "redBall")
    localBadGuy.name = "badguy"
    localBadGuy.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    localBadGuy.setScale(0)
    let scaleUp = SKAction.scaleTo(0.15, duration: 2)

    let moveToSide = SKAction.moveTo(CGPoint(x: CGFloat.random(min: 0 + 50, max: self.size.width - 50 ), y: CGFloat.random(min: 0 + 50, max: self.size.height - 50 )), duration: 2)
    localBadGuy.runAction(moveToSide)
    localBadGuy.runAction(scaleUp)
    self.addChild(localBadGuy)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */

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


        if touchedNode.name == "badguy"{

            touchedNode.removeFromParent()
        }
}

关于ios - 触摸时删除 SKSpriteNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37386423/

相关文章:

iphone - 接受应用程序更新后,您可以在 iTunes Connect 中删除应用程序更新吗

iOS 按钮和导航链接在列表中彼此相邻

ios - Xcode Scene Editor - 如何显示实体列表?

ios - 如何将 NSMutableOrderedSet 转换为泛型数组?

swift - 自动布局 ImageView 高度 anchor 在 Collection View 中发生冲突并且无法正常工作

ios - SpriteKit animateWithTextures 不适用于纹理图集

inheritance - 使用 swift 在子类中设置基类 'let' 变量

ios - SCLAlertView 库 - 如何从另一个 View Controller 触发它?

ios - 将 UINavigationBar 附加到 UIScrollView 以获得缩小的标题

swift - 在一个动画循环后隐藏 SKSpriteNode