如何在cocos2d中增加分数标签

时间:2012-03-28 15:27:13

标签: xcode cocos2d-iphone label increment

所以我有一个标签,我希望当图像与另一个图像碰撞时,它增加10。得分=得分+10;但不是这样,它增加了40我不知道为什么。所以这是我的代码:

-(id) init
{
    if( (self=[super init] )) {

        [self schedule:@selector(update:)];

        score = 0;

        scoreLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d",score] fontName:@"PUSAB___.TTF" fontSize:15 ];
        scoreLabel.position=ccp(450,30);
        [self addChild:scoreLabel];
    }
}

- (void)update:(ccTime)dt {
    if (CGRectIntersectsRect(mangeurRect, targetRect)) {
        [targetsToDelete addObject:target];     
        score=score + 10; ;// Not really, but your score changes somehow...
        [scoreLabel setString: [NSString stringWithFormat:@"%d",score]];
    }                       
}
抱歉我的英语我是法国人:/

3 个答案:

答案 0 :(得分:1)

我认为你在CGRectIntersectsRect中没有框架。您应该尝试以下代码

- (void)update:(ccTime)dt {

if (CGRectIntersectsRect([mangeurRect frame], [targetRect frame])) {
    [targetsToDelete addObject:target];     
    score += 10;
    [scoreLabel setString: [NSString stringWithFormat:@"%d",score]];
}                       

}

- (void)update:(ccTime)dt {

if (CGRectIntersectsRect([mangeurRect boundingBox], [targetRect boundingBox])) {
    [targetsToDelete addObject:target];     
    score += 10; 
    [scoreLabel setString: [NSString stringWithFormat:@"%d",score]];
}                       

}

通过这种方式,每当图像相互碰撞时,你可能会得分。

答案 1 :(得分:0)

如果实际清空targetsToDelete结构的进程以某种方式延迟了几个滴答,你应该检查你的目标是否还没有被删除的目标,如下所示:

- (void)update:(ccTime)dt {
    if ([targetsToDelete containsObject:target]) return;    // already scored.
    if (CGRectIntersectsRect(mangeurRect, targetRect)) {
        [targetsToDelete addObject:target];     
        score=score + 10; ;// Not really, but your score changes somehow...
        [scoreLabel setString: [NSString stringWithFormat:@"%d",score]];
    }                       
}

以上假设targetsToDelete是NSMutableArray。

答案 2 :(得分:0)

您的更新方法尚未完成。试试这个:

- (void)update:(ccTime)dt {
    if (CGRectIntersectsRect(mangeurRect, targetRect)) {
        [targetsToDelete addObject:target];     
        score=score + 10; ;// Not really, but your score changes somehow...
        [scoreLabel setString: [NSString stringWithFormat:@"%d",score]];

        //do something with your targetsToDelete array.. 
        for (CCSprite *target in targetsToDelete) {
         //[_targets removeObject:target]; //uncomment this line, if you have saved your targets in a _targets array
         [self removeChild:target cleanup:YES];                                 
        }
    }                       
}

参考:http://www.raywenderlich.com/352/how-to-make-a-simple-iphone-game-with-cocos2d-tutorial