touchesBegan如果声明问题

时间:2018-02-20 02:21:20

标签: ios swift sprite-kit

我试图检测节点是否是敌人。如果是,我想删除它。我尝试使用触摸的节点名称来检测这一点。我能够检测节点的名称是否是敌人,但我不知道如何删除它。谢谢您的帮助! :)

以下是所有相关代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self)
    let nodes = self.nodes(at: location);
    let name = nodes.first?.name;

    if (name == "enemy") {
        nodes.removeFromParent() // this doesn't work
    }
}

@objc open func spawnEnemies() {
    let randomNumber = randomBetween(min: Int(-150), max: Int(self.frame.width + 150))
    print(randomNumber)
    print(self.frame.width)
    var enemy = SKSpriteNode(imageNamed: "triangle")
    enemy.position = CGPoint(x: CGFloat(randomNumber), y: self.frame.height + 250)
    enemy.name = "enemy";
    enemy.zPosition = 6.0;

    enemy.physicsBody?.allowsRotation = false

    enemy.zRotation = 0
    enemy.physicsBody?.affectedByGravity = false
    enemy.physicsBody = SKPhysicsBody(texture: enemy.texture!, size: enemy.texture!.size())
    enemy.physicsBody?.affectedByGravity = false
    enemy.physicsBody?.isDynamic = true
    enemy.physicsBody?.categoryBitMask = enemyCategory
    enemy.physicsBody?.collisionBitMask = blockerCategory
    enemy.physicsBody?.contactTestBitMask = blockerCategory
    enemy.setScale(CGFloat(0.03))
    addChild(enemy)
}

1 个答案:

答案 0 :(得分:1)

这部分代码存在问题:

let nodes = self.nodes(at: location);
let name = nodes.first?.name;

if (name == "enemy") {
    nodes.removeFromParent() // this doesn't work
}

您的变量nodesSKNode个实例的数组;在整个数组上调用SKNode方法removeFromParent()没有任何意义(仅限于其各个元素)。

您已成功测试.first元素的名称;做同样的事情去除它:

let nodes = self.nodes(at: location);
let name = nodes.first?.name;

if (name == "enemy") {
    nodes.first?.removeFromParent()
}

或许是一个更好的apporach(在一轮中移除多个敌人):

for node in self.nodes(at: location) {
    if node.name == "enemy" {
        node.removeFromParent()
    }
}

最后,上面代码的更“swifty”版本:

nodes.filter({ (node) -> Bool in
    return node.name == "enemy"
}).forEach({ (enemy) in
    enemy.removeFromParent()
})