SpriteKit childNodeWithName找不到现有节点

时间:2014-08-30 11:14:08

标签: swift sprite-kit sknode

我在SKScene中有这段代码:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {

    var touch: AnyObject = touches.anyObject()
    var point = getPoint(touch.locationInNode(self))
    var name  = NSStringFromCGPoint(point)

    for children in self.children {

        if (children as SKSpriteNode).name == name {

            println("exist!")
        }
    }
    var tempNode = self.childNodeWithName(name)
}

我看到了#34;存在!"在日志中,所以在children数组中有一个具有此名称的节点,但 tempNode nil self.childNodeWithName("//" + name)调用也会返回 nil

2 个答案:

答案 0 :(得分:9)

以下是如何在Swift中完成此操作...希望这有帮助!

var mySprite: SKSpriteNode = childNodeWithName("mySprite") as SKSpriteNode

答案 1 :(得分:0)

我使用 Swift 2.2 发现了这种奇怪,可能是一个错误..你不能使用NSStringFromCGPoint和childNodeWithName而不清除大括号中的字符串:

使用这个小方法:

func removeBraces(s:String)->String {
    return s.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "{}"))
}

当您添加SKSpriteNode时,例如:

...
mySpriteNode.name = removeBraces(NSStringFromCGPoint(mySpriteNode.position))
...

并根据您的情况检索它:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {

    var touch: AnyObject = touches.anyObject()
    var point = getPoint(touch.locationInNode(self))
    var name  = removeBraces(NSStringFromCGPoint(point))
    if let child = self.childNodeWithName(name) {
        print("I've found: \(child)")
    }
    ...
}