我有一个for循环实例化5个精灵
for enemy in 1...5 {
negativeOnComing = SKSpriteNode(imageNamed: "Enemy3")
negativeOnComing.physicsBody = SKPhysicsBody(circleOfRadius: negativeOnComing.frame.size.width/2)
negativeOnComing.physicsBody?.dynamic = true
negativeOnComing.physicsBody?.categoryBitMask = PhysicsCategory.negativeOncoming
negativeOnComing.physicsBody?.fieldBitMask = PhysicsCategory.negativeOncoming
negativeOnComing.physicsBody?.contactTestBitMask = PhysicsCategory.mainCenterNode | PhysicsCategory.positiveOncoming
negativeOnComing.physicsBody?.node?.name = "negativeOnComing"
self.addChild(negativeOnComing)
} 我已经将变量全局声明为
var negativeOnComing : SKSpriteNode!
现在我希望能够移除轻敲后被点击的精灵。为了尝试这个我做了
func removeNegativeOncoming(negativeOnComingR:SKSpriteNode){
println("Tapped")
childNodeWithName("negativeOnComing")?.removeFromParent()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent){
var touch = touches.anyObject() as UITouch
var touchPosition = touch.locationInNode(self)
var enemyNodePosition = negativeOnComing.childNodeWithName("negativeOnComing")?.position
var enemyNodeFrame = negativeOnComing.frame
func removeEnemyNode (UITouch) -> SKSpriteNode {
if (enemyNodeFrame.contains(touchPosition) ) {
removeNegativeOncoming(negativeOnComing)
}
return negativeOnComing
}
mainSpriteMovement(touch)
}
现在这个函数实际上确实删除了精灵,但它不会删除精确点击的精灵,而是随机删除5个精灵中的一个。我的问题是我怎样才能将精灵只被删除,而不只是随机中的一个5.希望这个问题很好被问及可以理解。谢谢你们所有人
答案 0 :(得分:1)
您正在创建5个敌人,但每次都设置negativeOnComing
,因此此变量最终只会保留对最后创建的节点的引用。
然而,这不是您问题的原因。您正在使用childNodeWithName
来查找要删除的节点 - 但是您的所有敌人节点都具有相同的名称,因此您可以随机获取一个节点。
您只需使用nodeAtPoint
来确定点击了哪个节点 -
override func touchesBegan(touches: NSSet, withEvent event: UIEvent){
var touch = touches.anyObject() as UITouch
var touchPosition = touch.locationInNode(self)
var touchedNode = self.nodeAtPoint(touchPosition)
if (touchedNode.name == "negativeOnComing") {
touchedNode.removeFromParent()
}
mainSpriteMovement(touch)
}