如何获得SKSpriteNode名称?

时间:2014-12-03 21:07:17

标签: swift sprite-kit skspritenode

我正在使用我发现的代码,并试图弄清楚如何获取对象的节点名称?

以下是代码的一部分:

let sprite1 = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 30, height: 30))
let sprite2 = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 30, height: 30))
let sprite3 = SKSpriteNode(color: UIColor.blueColor(), size: CGSize(width: 30, height: 30))
let sprite4 = SKSpriteNode(color: UIColor.yellowColor(), size: CGSize(width: 30, height: 30))

var selected: [UITouch: SKNode] = [:]

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    selected = [:]
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        selected[touch as UITouch] = nodeAtPoint(location)

        println(self.name)
    }
}

我想要实现的是让println返回SKSprintNode名称(sprite1,sprite2,sprite3或sprite4)......我已经尝试过几件事了get是´nil´

这可能吗?

加了:

那么,为了跟进,我如何检测触摸是否在我的物体内?这是一些更多的代码:

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        for (touch, node) in selected{
            if !contains(SKScene, node){
                let action = SKAction.moveTo(location, duration: 0.1)
                node.runAction(SKAction.repeatAction(action, count: 1))
            }
        }

    }
}

使用if !contains(SKScene, node)(无效,无法在SKScene上测试)我想检测触摸是在对象上还是在外面。如果在外面(触摸是SKScene)我不想做任何事情..

我想以这种方式执行此操作并且不在let名称上测试sprite1的原因是我计划以编程方式创建所有SKSpriteNode,所以我不这样做必须知道node-object的名称..

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您正在设置变量的名称,但您没有设置SKSpriteNode的名称。它应该是:

 sprite1.name = @"sprite1";

跟随你精神的其他部分。

我注意到的另一件事是你打电话给self.name。我很确定self指的是场景,如果这是代码的位置。相反,您应该将选定内容保存为SKSpriteNode并调用selected.name。

相关问题