我正在爲一個學習項目構建一個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