How to get SKSpriteNode name?

别说谁变了你拦得住时间么 提交于 2019-12-11 04:16:00

问题


I'm working with this code I've found and trying to figure out how to get the node names for my objects?

Here's part of the code:

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

What I'm trying to achieve is to get the println to return the SKSprintNode name (sprite1, sprite2, sprite3 or sprite4)... I've tried several things, bit all I get is ´nil´.

Is this possible?

Added:

So, to follow up, how can I detect whether the touch is within my objects? Here's some more code:

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

    }
}

With the if !contains(SKScene, node) (which is not working, can't test on SKScene) I want to detect if the touch was on the object or outside.. If outside (touch is SKScene) I don't want to do anything..

The reason I want to do it this way and not test on let names as i.e sprite1 is that I'm planning to make all SKSpriteNode programmatically, so I don't necessary know the name of the node-object..

Any suggestions?


回答1:


You are setting the name of the variable, but you are not setting the name of the SKSpriteNode. It should be:

 sprite1.name = @"sprite1";

Follow suit for the rest of your sprites.

Another thing I noticed is that you call self.name. I am pretty sure self refers to the scene, if that is where this code is located. Instead, you should save the selected as an SKSpriteNode and call selected.name.



来源:https://stackoverflow.com/questions/27281640/how-to-get-skspritenode-name

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