2011-12-08 45 views
0

如果調用ccTouchesMoved函數,則移動手指範圍內的精靈必須添加到數組中。但只有一次。我得到的結果是它多次添加了觸摸的精靈(因爲當它移動到精靈的外部時,手指仍然在精靈上)。所以我把它封裝在if語句中,這應該避免這種情況。但它不......我該怎麼辦?ccTouchesMoved將對象添加到數組多次,即使if語句應該避免該對象

-(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); 
     } 


} 
+0

爲什麼將標籤存儲在數組中,爲什麼不直接存儲realSprite呢? – deanWombourne

+0

它有什麼區別嗎?我正在用'![hexTags containsObject:hexTag]'來檢查它是否已經包含之前添加的標記...如果我要比較對象,它不會有什麼區別,對吧? –

+0

這就是爲什麼這是一個評論,而不是一個答案;它看起來像做了很多的努力,使每個運動的對象只是爲了看看它是否已經在一個數組:) :) – deanWombourne

回答

0

你爲什麼不使用NSSet(或NSMutableSet)呢?除非你想保留將精靈添加到列表中的順序,否則NSMutableSet更適合你的情況。您甚至不必檢查精靈是否已添加到列表中,因爲它是由NSMutableSet在內部完成的。此外,由於NSSet使用對象散列,所以在NSSet上調用containsObject:進行了優化。

+0

其實,這個命令必須保存......但是,無論如何,謝謝你 –

相關問題