SpriteKit childNodeWithName can't find existing node

前提是你 提交于 2019-12-11 05:58:42

问题


I have this code in 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)
}

I see "exist!" in log, so there is a node with this name in children array, but tempNode is nil. The self.childNodeWithName("//" + name)call returns nil too.


回答1:


Here is how to accomplish this in Swift... Hope this helps!

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



回答2:


I've found this strangeness using Swift 2.2, maybe a bug .. you can't use NSStringFromCGPoint and childNodeWithName without cleaning the string from braces:

Using this little method:

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

when you add your SKSpriteNode do for example:

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

and to retrieve it for your case :

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)")
    }
    ...
}


来源:https://stackoverflow.com/questions/25581738/spritekit-childnodewithname-cant-find-existing-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!