我已准备好游戏,现在我正在尝试重构代码。我从CCNode派生了Spider类,并使用了目标委托方法CCTargetedTouchDelegate。
@interface Spider : CCNode<CCTargetedTouchDelegate> {
CCSprite* spiderSprite;
NSString * spiderKilled;
int killed;
AppDelegate *del;
}
+(id) spiderWithParentNode:(CCNode*)parentNode;
-(id) initWithParentNode:(CCNode*)parentNode;
@end
On Touch蜘蛛应该被杀死,这里是代码:
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint tch = [touch locationInView: [touch view]];
CGPoint touchLocation = [[CCDirector sharedDirector] convertToGL:tch];
// Check if this touch is on the Spider's sprite.
BOOL isTouchHandled = CGRectContainsPoint([spiderSprite boundingBox], touchLocation);
if (isTouchHandled)
{
j = j + 1;
killed ++;
[del setKilledScore:j];
[self removeChild:spiderSprite cleanup:YES];
}
return isTouchHandled;
}
我使用以下方法在GameScene图层中添加10个蜘蛛: -
for(int i=0; i <10 ;i++){
[Spider spiderWithParentNode:self];
}
但是,遗憾的是我无法移除蜘蛛并在此行中出现EXC_BAD_ACCESS错误:[self removeChild:spiderSprite cleanup:YES];
请帮我克服这个错误。
由于
更新 - 蜘蛛初始化代码 //静态自动释放初始化程序,模仿cocos2d的内存分配方案。 +(id)spiderWithParentNode:(CCNode *)parentNode { return [[[self alloc] initWithParentNode:parentNode] autorelease]; }
-(id) initWithParentNode:(CCNode*)parentNode
{
if ((self = [super init]))
{
[parentNode addChild:self];
del = [[UIApplication sharedApplication] delegate];
CGSize screenSize = [[CCDirector sharedDirector] winSize];
spiderSprite = [CCSprite spriteWithFile:@"spider.png"];
spiderSprite.position = CGPointMake(CCRANDOM_0_1() * screenSize.width, CCRANDOM_0_1() * screenSize.height);
[self addChild:spiderSprite];
// Manually add this class as receiver of targeted touch events.
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:-1 swallowsTouches:YES];
}
return self;
}
答案 0 :(得分:0)
如果您手动将类添加到CCTouchDispatcher列表中,则应在使用完毕后将其从该列表中删除。