1

我在 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)
}

我看到“存在!” 在日志中,因此 children 数组中有一个具有此名称的节点,但 tempNodenil。该self.childNodeWithName("//" + name)调用也返回nil

4

2 回答 2

10

以下是如何在 Swift 中完成此操作……希望对您有所帮助!

var mySprite: SKSpriteNode = childNodeWithName("mySprite") as SKSpriteNode
于 2014-11-04T19:33:18.413 回答
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)")
    }
    ...
}
于 2016-03-29T14:40:52.827 回答