我有一个游戏,用户收集不同类型的对象和一开始值为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));
}
}
}
答案 0 :(得分: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;
}
}
}
答案 1 :(得分:0)
score = score + 1;
[scoreLabel1 setString:[NSString stringWithFormat:@"%@", score]];
%@ - Objective-C对象,打印为descriptionWithLocale:
返回的字符串(如果可用)或其他描述。也适用于CFTypeRef
个对象,返回CFCopyDescription
函数的结果。
如果您的score
是一个对象,则不能以这种方式“递增”其值。如果它是int或float,则使用错误的格式说明符。