Objective c ccTouchesMoved多次将对象添加到数组中,即使if语句应该避免这样做
如果调用ccTouchesMoved函数,则必须将移动手指范围内的精灵添加到阵列中。但只有一次。我得到的结果是,它多次添加被触摸的精灵(因为手指向精灵外部移动时仍在精灵上)。所以我把它封装到一个if语句中,这应该可以避免这种情况。但它不。。。我该怎么办Objective c ccTouchesMoved多次将对象添加到数组中,即使if语句应该避免这样做,objective-c,cocos2d-iphone,Objective C,Cocos2d Iphone,如果调用ccTouchesMoved函数,则必须将移动手指范围内的精灵添加到阵列中。但只有一次。我得到的结果是,它多次添加被触摸的精灵(因为手指向精灵外部移动时仍在精灵上)。所以我把它封装到一个if语句中,这应该可以避免这种情况。但它不。。。我该怎么办 -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *myTouch = [touches anyObject]; CGPoin
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
CCSprite* realSprite = [self whichHexagonTouched:convertedLocation];
NSNumber *hexTag = [NSNumber numberWithInt:realSprite.tag];
// If the hexagon is not in the array and not nil, it should destroy it and add it to the array
if(realSprite != nil && ![hexTags containsObject:hexTag]){
[self destroyHexagon:realSprite];
[hexTags addObject:hexTag];
NSLog(@"these are the hexTags %@", hexTags);
}
}
为什么不改用
NSSet
(或NSMutableSet
)呢?除非您希望保留精灵添加到列表的顺序,NSMutableSet
更适合您的情况。您甚至不必检查精灵是否已添加到列表中,因为它是由NSMutableSet
内部完成的。另外,在NSSet
上调用containsObject:
是优化的,因为它使用对象散列。为什么要将标记存储在数组中,为什么不只存储realSprite?这有什么区别吗?我正在检查![hexTags containsObject:hexTag]
是否已包含之前添加的标记。。。如果我比较物体,它不会有任何区别,对吗?这就是为什么这是一个评论,而不是一个答案;似乎每次移动都要做一个对象,只是为了看看它是否已经在数组中:)好吧,无论如何,谢谢:)。。。我希望我能很快解决这个问题…事实上,秩序必须得到维护。。。不过还是谢谢你