Swift + Sprite 套件触摸检测
Swift + Sprite Kit Touch Detection
我只是想知道如何从场景中删除 SKSprite 节点。这是我目前所拥有的:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = (touch as UITouch).locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "monster" {
monster! .removeFromParent()
}
}
}
}
我在屏幕上创建了很多这样的怪物,但是当我点击其中一个时,它没有任何反应。如果我尝试添加 println("touched")
,它会告诉我它已被触及。
你在跟踪你的怪物吗?如果没有,请通过将它们添加到可变数组来跟踪它们。还为每个精灵添加唯一名称。
然后只需将该对象与您的数组进行比较并删除该对象。希望这有帮助.. :)
当您执行 monster.removeFromParent()
时,这不会删除被触及的节点,因为 monster
不是对被触及的节点的引用。要删除被触摸的节点,您可以使用以下代码:
for touch in touches {
let location = (touch as UITouch).locationInNode(self)
if let theMonster = self.nodeAtPoint(location)
if theMonster.name == "monster" {
theMonster.removeFromParent()
}
}
}
我只是想知道如何从场景中删除 SKSprite 节点。这是我目前所拥有的:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = (touch as UITouch).locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "monster" {
monster! .removeFromParent()
}
}
}
}
我在屏幕上创建了很多这样的怪物,但是当我点击其中一个时,它没有任何反应。如果我尝试添加 println("touched")
,它会告诉我它已被触及。
你在跟踪你的怪物吗?如果没有,请通过将它们添加到可变数组来跟踪它们。还为每个精灵添加唯一名称。
然后只需将该对象与您的数组进行比较并删除该对象。希望这有帮助.. :)
当您执行 monster.removeFromParent()
时,这不会删除被触及的节点,因为 monster
不是对被触及的节点的引用。要删除被触摸的节点,您可以使用以下代码:
for touch in touches {
let location = (touch as UITouch).locationInNode(self)
if let theMonster = self.nodeAtPoint(location)
if theMonster.name == "monster" {
theMonster.removeFromParent()
}
}
}