触摸cocos2D中的精灵会使我的应用程序崩溃

时间:2012-02-28 21:17:16

标签: iphone xcode crash cocos2d-iphone touch

我的代码有问题:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
CGRect MoveableSpriteRect =CGRectMake(oeuf1.position.x -(oeuf1.contentSize.width/2),oeuf1.position.y-(oeuf1.contentSize.height/2),oeuf1.contentSize.width,oeuf1.contentSize.height);

if (CGRectContainsPoint(MoveableSpriteRect, location)) {
    [self removeChild:oeuf1 cleanup: YES];
    [self removeChild:ombreOeuf1 cleanup: YES];
}
}

当我触摸 oeuf1 时,它会像我想要的那样消失,但如果我再次触摸屏幕我的应用程序崩溃我不知道为什么?我该怎么解决这个问题?谢谢 。对不起我的英语我是法国人:/

2 个答案:

答案 0 :(得分:2)

CGRect MoveableSpriteRect =CGRectMake(oeuf1.position.x -(oeuf1.contentSize.width/2),oeuf1.position.y-(oeuf1.contentSize.height/2),oeuf1.contentSize.width,oeuf1.contentSize.height);在删除后仍然引用oeuf1,因此会导致EXC_BAD_ACCESS错误。解决此问题的最简单方法是在标头文件中声明BOOL,并在删除YEStrue时将其设置为oeuf1 / ombreOeuf1。然后,如果BOOL为真,则不要运行

CGRect MoveableSpriteRect =CGRectMake(oeuf1.position.x -(oeuf1.contentSize.width/2),oeuf1.position.y-(oeuf1.contentSize.height/2),oeuf1.contentSize.width,oeuf1.contentSize.height);

if (CGRectContainsPoint(MoveableSpriteRect, location)) {
    [self removeChild:oeuf1 cleanup: YES];
    [self removeChild:ombreOeuf1 cleanup: YES];
}

编辑:

.h文件中添加:

@interface .... {
    ...
    BOOL oeuf1Removed; // Feel free to translate this to French!
}

然后将-touchesBegan更改为:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    if (!oeuf1Removed) {
        CGRect MoveableSpriteRect = CGRectMake(oeuf1.position.x -(oeuf1.contentSize.width/2),oeuf1.position.y-(oeuf1.contentSize.height/2),oeuf1.contentSize.width,oeuf1.contentSize.height);

        if (CGRectContainsPoint(MoveableSpriteRect, location)) {
            [self removeChild:oeuf1 cleanup: YES];
            [self removeChild:ombreOeuf1 cleanup: YES];
            oeuf1Removed = YES;
        }
    }
}

答案 1 :(得分:0)

这样做

if (oeuf1) {
CGRect MoveableSpriteRect = CGRectMake(oeuf1.position.x -(oeuf1.contentSize.width/2),
                                       oeuf1.position.y-(oeuf1.contentSize.height/2),
                                       oeuf1.contentSize.width,oeuf1.contentSize.height);
}

而不仅仅是

CGRect MoveableSpriteRect = CGRectMake(oeuf1.position.x -(oeuf1.contentSize.width/2),
                                       oeuf1.position.y-(oeuf1.contentSize.height/2),
                                       oeuf1.contentSize.width,oeuf1.contentSize.height);

如果你想问题的原因看起来@下面的答案