我正在为一个研究项目构建一个 iPad 游戏,但我一直试图让我的一个对象(从 CCSprite 继承)来调用 CCLayer 上的一个函数。
情况:我的 CCLayer 上有一个 wordObject 实例(继承自 CCSprite)。当对象被触摸时,它会记录一些东西并应该在它的父级 CCLayer 上执行一个函数来创建一个新对象。
到目前为止,我所拥有的检测到触摸并记录了一条消息,但我找不到在 CCLayer 上执行该功能的方法,因此我提出了问题。
当用另一种语言编程时,我只需将 CCLayer 指针作为参数传递给我的对象的 init 函数。我尝试通过这种方式扩展 initWithSprite 函数来做到这一点:
//touch function
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView: [touch view]];
if (CGRectContainsPoint([self boundingBox], location)) {
CCLOG(@"Woah");
[parentLayer foundWord:@"test" atLocation:ccp(100.0f, 100.0f) withZValue:(int)1000 andPoints:100];
CCLOG(@"Delegate should have executed");
return YES;
}
CCLOG(@"Touch detected, I'm located at %@ and the touch position is %@.", NSStringFromCGRect([self boundingBox]), NSStringFromCGPoint(location));
return NO;
}
// Extended init function, I have no normal init function anymore (but I don't think I need that, tried it and it gave crashes
-(id)initWithSpriteFrame:(CCSpriteFrame*)spriteFrame andParent:(CCLayer *)layer{
[super initWithSpriteFrame:spriteFrame];
self = [super init];
if(self != nil){
parentLayer = layer;
}
return self;
}
问题是使用此对象后,对象不再响应触摸输入(这可能是由于我在对象初始化时做错了什么造成的)。
但是,还有另一种方法可以做到这一点,据我了解,这种方法在 Objective C 中更好。我应该能够为我需要的函数创建一个协议,然后使用委托在我的对象中调用该函数。我为此编写的代码:
//CommonProtocols.h the file with the protocols. It is included in the CCLayer and in the object
@protocol GameplayScrollingLayerDelegate
-(void)foundWord:(NSString *)word atLocation:(CGPoint)location withZValue:(int)ZValue andPoints:(int)points;
@end
//Layer.h, subscribing the class to the protocol so it knows where it should delegate to
@interface Layer : CCLayer <GameplayScrollingLayerDelegate> {
//some stuff omitted due to not being relevant.
}
//Layer.m, nothing done here, I've just added the function which I described in the protocol file
-(void)foundWord:(NSString *)word atLocation:(CGPoint)location withZValue:(int)ZValue andPoints:(int)points{
// Function gibberish doing what I want it to do
}
//Object.h create the delegate
@interface Object : GameObject <CCTargetedTouchDelegate> {
id <GameplayScrollingLayerDelegate> delegate;
}
@property (nonatomic,assign) id <GameplayScrollingLayerDelegate> delegate;
//Object.m synthesize the delegate and try to execute the function
@synthesize delegate
//... code omitted ...
-(id)init{
//default init stuff
[delegate foundWord:@"test" atLocation:ccp(100.0f, 100.0f) withZValue:(int)1000 andPoints:100];
}
我缺乏使用协议或接口的知识可能导致我在此过程中遗漏了一些东西。尽管它没有给我任何错误或警告,但它也没有像我想要的那样执行该功能。(我有一个正在使用它的演示应用程序,它工作得很好,但我就是找不到我丢失的那段代码)。
关于如何解决这个问题的任何建议?感谢阅读并希望能回答我的问题!