我试图在点击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()
}
我在两个完全不同的项目中遇到了同样的问题,并且无法找到解决方案。任何帮助都会非常感激!
答案 0 :(得分:0)
因为您正在编写相同的变量。尝试:
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()
}
}
答案 1 :(得分:0)
在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;
}
}
}