首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >代码重构问题

代码重构问题
EN

Stack Overflow用户
提问于 2011-12-07 06:29:28
回答 1查看 113关注 0票数 1

我已经准备好游戏,现在我正在尝试重构代码。我从CCNode派生了Spider类,并使用了目标委托方法CCTargetedTouchDelegate。

代码语言:javascript
复制
@interface Spider : CCNode<CCTargetedTouchDelegate> {
    CCSprite* spiderSprite;
    NSString * spiderKilled;
    int killed;
    AppDelegate *del;
}

+(id) spiderWithParentNode:(CCNode*)parentNode;
-(id) initWithParentNode:(CCNode*)parentNode;

@end

触碰蜘蛛应该被杀死,下面的代码是:

代码语言:javascript
复制
-(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只蜘蛛,使用:-

代码语言:javascript
复制
 for(int i=0; i <10 ;i++){
      [Spider spiderWithParentNode:self];
    }

但是,不幸的是,我无法删除蜘蛛并在这行中给出EXC_BAD_ACCESS错误:[self removeChild:spiderSprite cleanup:YES];

请帮我克服这个错误。

谢谢

更新- Spider代码//静态自动释放初始化器,模拟cocos2d的内存分配方案。+(id) spiderWithParentNode:(CCNode*)parentNode {返回[[self alloc initWithParentNode:parentNode]自动释放];}

代码语言:javascript
复制
-(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;
}
EN

回答 1

Stack Overflow用户

发布于 2012-01-16 12:10:39

如果手动将类添加到CCTouchDispatcher列表中,则在使用完该类之后,应该将其从该列表中删除。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8411284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档