将Objective-C代码转换为Swift时遇到了一个问题。我在SKScene子类中添加了两个精灵。第一个精灵直接添加到场景中,第二个精灵是第一个节点的子节点。当我点击任一精灵时,游戏应该记录精灵的名字。这在Objective-C版本中按预期工作,但无论我点击哪个节点,Swift版本都会记录“sprite1”。
目标C
声明精灵并将它们添加到场景
CGSize size = CGSizeMake(32, 32);
SKSpriteNode *sprite1 = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:size];
sprite1.name = @"sprite1";
sprite1.position = CGPointMake(100, 100);
[self addChild:sprite1];
SKSpriteNode *sprite2 = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:size];
sprite2.name = @"sprite2";
sprite2.position = CGPointMake(150, 100);
[sprite1 addChild:sprite2];
触控处理程序
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:@"sprite2"]) {
NSLog(@"sprite2");
}
if ([node.name isEqualToString:@"sprite1"]) {
NSLog(@"sprite1");
}
}
}
夫特
声明精灵并将它们添加到场景
let size = CGSizeMake(32, 32)
let sprite1 = SKSpriteNode(color: SKColor.blueColor(), size: size)
sprite1.name = "sprite1"
sprite1.position = CGPointMake(100, 100)
self.addChild(sprite1)
let sprite2 = SKSpriteNode(color: SKColor.redColor(), size: size)
sprite2.name = "sprite1"
sprite2.position = CGPointMake(150, 100)
sprite1.addChild(sprite2)
触控处理程序
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)
if (node.name == "sprite2") {
println("sprite2")
}
if (node.name == "sprite1") {
println("sprite1")
}
}
}
答案 0 :(得分:2)
您正在将sprite2.name
设置为“sprite1。”
let size = CGSizeMake(32, 32)
let sprite1 = SKSpriteNode(color: SKColor.blueColor(), size: size)
sprite1.name = "sprite1"
sprite1.position = CGPointMake(100, 100)
self.addChild(sprite1)
let sprite2 = SKSpriteNode(color: SKColor.redColor(), size: size)
sprite2.name = "sprite1" //here
sprite2.position = CGPointMake(150, 100)
sprite1.addChild(sprite2)
将其更改为“sprite2。”
let size = CGSizeMake(32, 32)
let sprite1 = SKSpriteNode(color: SKColor.blueColor(), size: size)
sprite1.name = "sprite1"
sprite1.position = CGPointMake(100, 100)
self.addChild(sprite1)
let sprite2 = SKSpriteNode(color: SKColor.redColor(), size: size)
sprite2.name = "sprite2"
sprite2.position = CGPointMake(150, 100)
sprite1.addChild(sprite2)