【发布时间】:2013-03-17 06:00:50
【问题描述】:
我有一个游戏,其中用户收集不同类型的对象和一个在开始时值为 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));
}
}
}
【问题讨论】:
-
如果你想删除而不是隐藏,使用方法
[ object removeFromParentAndCleanup: true ]。也为了将来,请不要同时问两个问题。而是写两个问题。 -
嗨,dghendricks,感谢您的帮助。我试过 [apple removeFromParentAndCleanup: true] 似乎没有用。苹果仍然会留在那里但不可见,所以当我继续按下它时,它会继续在分数标签上添加一个点。
-
如果你打电话给
[apple removeFromParentAndCleanup: true],那么苹果就不可能停留在屏幕上。要么你看到一个不同的苹果,你实际上并没有调用[apple removeFromParentAndCleanup: true],或者你正在其他地方存储对苹果的引用(一个数组?)并根据苹果的位置属性触发来自不同对象的点击,无论是否is 实际上是否在屏幕上。 -
是的,我调用了它,它确实使苹果不可见,但它仍然停留在屏幕上,你看不到它,但当你点击它时它就在那里,因为它会增加分数。掉落的苹果是从包含 5 个苹果的 appleArray 中调用的。我使用 for 循环让苹果 1 比 1 落在屏幕上
-
所以听起来最后一种情况是正确的。它们实际上并不在屏幕上,也不包含在任何视图中或处理任何点击事件,它们只是在一个数组中,您有一些其他对象(处理点击事件)循环查看它们是否被点击。您还需要从该数组中删除它们以解决您的问题。
标签: objective-c cocos2d-iphone