【问题标题】:Swift + Sprite Kit Touch DetectionSwift + Sprite Kit 触摸检测
【发布时间】:2015-01-07 00:02:12
【问题描述】:

我只是想知道如何从场景中移除一个 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"),它会告诉我它已被触摸。

【问题讨论】:

  • 你给你的每一个怪物起名为“怪物”吗?你把所有怪物的 userInteractionEnabled 设置为 true 了吗?

标签: ios swift sprite-kit


【解决方案1】:

当您执行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()
        }
    }
}

【讨论】:

    【解决方案2】:

    你在跟踪你的怪物吗?如果没有,请通过将它们添加到可变数组来跟踪它们。还要为每个精灵添加唯一的名称。

    然后将对象与您的数组进行比较并删除该对象。希望这会有所帮助.. :)

    【讨论】:

    • 我该怎么做?我的物品永远下落。我已经将其编程为每 0.5 秒将屏幕上方的精灵设置为随机位置,然后跌落。谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多