0

我有一个游戏,用户收集不同类型的对象和一开始值为 0 的标签。每次用户收集一个对象(通过触摸它)它应该使分数 = 当前分数 + 1;我已尝试使用以下代码,但是当我单击该对象时它会崩溃。

这是我的分数标签的代码,它在屏幕上显示 0:

score = 0;
scoreLabel1 = [CCLabelTTF labelWithString:@"0" fontName:@"Times New Roman" fontSize:33];
scoreLabel1.position = ccp(240, 160);
[self addChild:scoreLabel1 z:1];

这是我每次触摸对象时调用的 void 函数:

- (void) addScore
{
    score = score + 1;
    [scoreLabel1 setString:[NSString stringWithFormat:@"%@", score]];
}

这是我放置用于触摸对象的代码的实际部分:

-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self ccTouchesMoved:touches withEvent:event];

UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];

for (Apple in self.appleArray)
{
    if (CGRectContainsPoint(Apple.boundingBox, location))
    {
        [self addScore]; 
        Apple.visible = NO;            
    }
}

除了分数,其他一切都有效。还有一种方法可以让苹果消失,而不是让 apple.visible = false 让它不可见?因为这样苹果仍然存在但不可见,我想摆脱它。

希望有人可以提供帮助!

如果您有任何问题,请告诉我。

谢谢。

这是我画苹果的地方:

    -(id) init
    {
        // always call "super" init
        // Apple recommends to re-assign "self" with the "super's" return value

    if( (self=[super init]) ) {
    isTouchEnabled_ = YES;
    self.appleArray = [CCArray arrayWithCapacity:20];

        for (int i = 0; i < 5; i++) {

            Apple = [CCSprite spriteWithFile:@"Apple4.png"];
            [self addChild:Apple];
            [appleArray addObject:Apple];
        }
     [Apple removeFromParentAndCleanup:true];
     [self scheduleUpdate];

     }
     return self;
}

这是屏幕更新的地方:

-(void) update: (ccTime) dt
{
for (int i = 0; i < 5; i++) {

    Apple = ((CCSprite *)[appleArray objectAtIndex:i]);
    if (Apple.position.y > -250) {
        Apple.position = ccp(Apple.position.x, Apple.position.y - (Apple.tag*dt));
    }
}

}

4

2 回答 2

1

这里有几件事。在 setScore 中,您的格式被破坏并会导致崩溃(%@ 需要 NSObject*)。尝试:

[scoreLabel1 setString:[NSString stringWithFormat:@"%i", score]];

此外,你的 for 循环的语法很奇怪。尝试

for (Apple *anyApple in self.appleArray)
{
    if (CGRectContainsPoint(anyApple.boundingBox, location))
    {
        if (anyApple.visible) {
            [self addScore]; 
            anyApple.visible = NO; 
        }           
    }
}
于 2013-03-13T07:16:01.370 回答
0
score = score + 1;
[scoreLabel1 setString:[NSString stringWithFormat:@"%@", score]];

请阅读:字符串格式说明符

%@ - Objective-C 对象,如果可用,则打印为返回的字符串descriptionWithLocale:,否则打印为描述。也适用于CFTypeRef对象,返回CFCopyDescription函数的结果。

如果 yourscore是一个对象,则不能以这种方式“增加”它的值。如果它是 int 或 float,则说明您使用了错误的格式说明符。

于 2013-03-13T07:16:13.010 回答