【发布时间】:2011-12-07 06:29:28
【问题描述】:
我已经准备好游戏,现在我正在尝试重构代码。我从 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;
}
【问题讨论】:
-
请添加初始化spiderSprite的代码并添加到视图层次结构中。
-
我在最后添加了蜘蛛初始化代码..
标签: cocos2d-iphone