我正在为一个学习项目构建一个iPad游戏,并且我试图让我的一个对象(它继承自CCSprite)调用CCLayer上的函数。Cocos2d在其中的一个孩子中执行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];
}
我缺乏使用协议或接口的知识可能会导致我在该过程中忽略某些内容。尽管它不会给我任何错误或警告,但它不会像我想要的那样执行功能。 (我有使用它的演示应用程序,它的工作原理完美,但我找不到我缺少的代码片段)。
关于如何解决这个问题的任何建议?感谢阅读并希望回答我的问题!
感谢您的快速响应!你真棒,只是解决了我一直在打破我头两天的问题。我不知道我能做到这一点,看到对象的父母是CCSpriteBatchNode我不得不使它self.parent.parent,但它仍然工作。非常感谢你为这个解决方案! – 2011-03-09 16:26:20