Reputation: 948
I'm trying to delete SKSpriteNodes when they are tapped, however, I can't get the node that I want to be removed, just the latest one created. And because the nodes are spawned every second, when I tap on one it deletes the next one. Here is my code:
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()
}
I have had the same problem in two completely different projects and haven't been able to figure out a solution. Any help would be really appreciated!
Upvotes: 1
Views: 837
Reputation: 514
In Swift 4
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let touchedNode = self.atPoint(location)
if touchedNode.name == "badguy"{
touchedNode.removeFromParent()
break;
}
}
}
Upvotes: 2
Reputation: 2832
Because you are writing the same variable. try:
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()
}
}
Upvotes: 1