I'm having a bit of difficultys with detecting collision from two seperate NSMutableArrays. I have figured out that you cant just nest a for loop inside of another, because I need to make changes(delete both of the items from each array if they collide). It works sometimes but most of the times it crashes. this is my current attempt:
Code:
for (int objectCounter1=[object1Array count]-1; objectCounter1>= 0; objectCounter1--){
for (int objectCounter2=[object2Array count]-1; objectCounter2>= 0; objectCounter2--){
UIImageView *Object1 = [object1Array objectAtIndex:objectCounter1];
UIImageView *Object2 = [object2Array objectAtIndex:objectCounter2];
if( CGRectIntersectsRect(Object1.frame, Object2.frame)) {
[Object1 removeFromSuperview];
[object1Array removeObjectAtIndex:objectCounter1];
Object 1 = nil;
[Object2 removeFromSuperview];
[object2Array removeObjectAtIndex:objectCounter2];
Object2= nil;
score = score+50;
}
}
}
This does not work. It crashes every few times, saying something along the lines of [NSMutableArray objectAtIndex:] index 2 beyond bounds (0....1).
This is very complicating explaining why it doesnt work, but here you go.
say if you start with 3 items in each array. item one at index 0, item 2 at index 1, and item 3 at index 2. If you loop through the array and item 2 from both arrays collide. Then they both get deleted at the index they were found. But, the for loop is still going, and It still thinks there is an Index where both of the items were deleted, so it tries to run the loop attempting to get objectatindex:2, even though an Item has just been deleted from each array, so that means only 2 objects left in each array(the bound being 0...1) .
is there any way I can accomplish this task without getting the crash and it working fully functional? Thanks a million in advance.