问题
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