我的屏幕上有两个sprite节点:child1和child2,它们都继承自父节点。父级具有child1和child2都覆盖的"customAction"方法。它们都继承自skspritenode。
现在,在我的触摸开始我使用行
SKSpriteNode*touchedNode=(SKSpriteNode*)[self-nodeAtPoint:positionInScene];
但是,如果被触摸的节点类型为child1,我想从child1调用customAction的child1版本,如果是child2,我想调用child2版本。
除了标记精灵,然后使用switch语句将节点类型转换为其相应的子类型之外,还有什么"漂亮"或"更好"的方法可以做到这一点吗?
谢谢!
编辑:编码
// parent class
@interface animal : SKSpriteNode
-(int)getID;
-(void)yell;
@end
@implementation Animal
{
int animalID;
bool clickable;
}
-(id)initAnimalWithIDWithImage:(int)ID :(NSString *)animalType
{
NSDictionary * returnedAnimal = [animalParser getAnimalByType:animalType];
NSString *Icon = [returnedAnimal objectForKey:@"Icon"];
self = [super initWithImageNamed:Icon];
animalID = ID;
return self;
}
-(int)getID
{
return animalID;
}
-(void)yell
{
// **todo**
}
@end
// child1
@interface bear : animal
-(void)yell;
@end
@implementation bear
-(id)initBearWithID:(int)ID
{
return [super initAnimalWithIDWithImage:ID :@"Bear"];
}
-(void)yell
{
// **todo**
}
@end
// child2
@interface boar: animal
-(void)yell;
@end
// identical to bear
// in the scene
-(id)initGameScene:(CGSize)size :(int)mode
{
[self initialize:size];
if(self = [super initWithSize:size])
{
bear testBear = [[Bear alloc] initBearWithID:idCount++];
testBear.position = CGPointMake(300,300);
[self addChild:testBear];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
// problem solved!
// this is wrong
// SKSpriteNode * touchedNode = (SKSpriteNode *)[self nodeAtPoint:positionInScene];
// this is right
animal *touchedNode = (animal *)[self nodeAtPoint:positionInScene];
[touchedNode yell];
// need to something like if touchedNode is a bear do bear yell.. if boar do boar yell
}
考虑到您发布的代码,[touchedNode yell];
就是您所需要的。动态消息调度负责其余部分。如果您的节点可能不会实现yell
,请首先使用respondsToSelector:
进行检查。
要回答如何显式识别thpe的问题,可以使用isKindOfClass
。即if ([touchedNode isKindOfClass:[bear class]])
。
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isKindOfClass:
另外,用大写字母开头命名类。如果你遵循惯例,比如定期命名类和访问者,你的应用程序中的很多东西都会更好地工作。