SpriteKit childNodeWithName can't find existin

2019-08-01 22:27发布

问题:

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