我如何检查已被触摸的 SKSpriteNode 是否也是从 SKSpriteNode 继承的其他类型?

How can I check if a SKSpriteNode that has been touched also of some other type that inherits from SKSpriteNode?

我需要检查我的哪个自定义 - class SKSpriteNode 继承对象被触及。我的游戏中有一些元素,例如:

@interface Hero : SKSpriteNode

和一个非播放角色元素:

@interface StaticLevelElement : SKSpriteNode  

并且我需要检查哪个被触摸并相应地调用正确的方法(方法来自 Hero 或来自 StaticLevelElement class)。

我可以使用哪种方法来区分 classes 的特定类型?

你可以这样做:

if ([node isKindOfClass:[StaticLevelElement class]]){
     NSLog(@"Touched node is StaticLevelElement");

}else if([node isKindOfClass:[Hero class]]){
    NSLog(@"Touched node is Hero");
}

来自关于 isKindOfClass 的文档:方法:

Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

看这部分:

...or an instance of any class that inherits from that class

你应该小心,因为如果你像这样继承 StaticLevelElement

@interface SubclassOfStaticLevelElement : StaticLevelElement

@end

在 touchesBegan 中执行此操作:

if ([node isKindOfClass:[StaticLevelElement class]]){

     NSLog(@"Touched node is StaticLevelElement");
}

如果您同时触摸 StaticLevelElementSubclassOfStaticLevelElement 的实例,该方法将 return 为真。这是因为 SubclassOfStaticLevelElement 继承自 StaticLevelElement.

所以我想这不是最适合您的方法。在 SpriteKit 中,在像你这样的情况下,人们经常使用下面的方法(通过设置 SKNode's name 属性)。

在您的 Hero's 初始化程序中(或者您可以在场景中创建节点时命名):

self.name = @"hero";

然后在你的 touchesBegan:

if ([node.name isEqualToString:@"hero"]){
    NSLog(@"Touched node is hero");
}

您可以只覆盖您的 SKSpriteNode 子 类 中的 touchesBegan 方法,并相应地执行它们的功能。这为错误留下了最少的更改,因为只有在系统确定特定节点已被触摸时才会调用此方法。

如果你需要从主场景调用某种方法,你可以使用NSNotificationCenter向场景发送消息(如果你需要与许多不同的对象通信,这也可以, ) 你可以通过让英雄有一个存储场景实例的 属性 来调用场景方法,或者你可以有一个叫做 isTouched 的 属性,当你在 touchesBegan 和 false(否)中 当您在 touchesEndedtouchesCancelled 中时,连同某种标识 属性 以消除进行广泛搜索的需要,并且几乎像

这样打电话
  if(node.isTouched && node.identifier == "StaticLevelElement")
  {
       //do stuff pertaining to StaticLevelElement 
  }