5

I'm having problems with this method. I have two rectangles that are obviously contained within each other.(I've even graphed their coordinates manually to make sure.) When I use CGRectContainsRect to compare these two rectangles, it returns false. For the life of me, I have tried everything, scoured the net, and I can't find an answer to this problem. Anyone have any idea why? I've included the values for the CGRects when I debug to show that they are definitely within each other.

-(bool)checkBoundingBox {
    bool returnItem = YES;

    //Checks for sprite interaction
    for (int i = 0; i < [arrGameItems count]; i++) {
        CGRect rect2 = [[self getChildByTag:1] boundingBox];
        CGRect rect1 = [[self getChildByTag:3] boundingBox];

        //        rect1 = CGRectStandardize(rect1);
        //        rect2 = CGRectStandardize(rect2);

        if (CGRectContainsRect(rect2, rect1)) {
            CCLOG(@"removed child b*&ch");
            [self removeChildByTag:[arrGameItems count] cleanup:YES];
            returnItem = NO;
        }
    }   

    CCLOG(@"g-dammit");    
    return returnItem;
}

rect1 origin x = 141 y = 76, height = 25, width = 25

rect2 origin x = 127 y = 91, height = 25, width = 25

eric.mitchell
  • 8,817
  • 12
  • 54
  • 92
drucifer
  • 65
  • 1
  • 7

2 Answers2

24

CGRectContainsRect() checks if one rectangle completely encompasses another, not just if they intersect. From your coordinates, the rectangles don't contain each other, but just intersect. You're looking for CGRectIntersectsRect().

Itai Ferber
  • 28,308
  • 5
  • 77
  • 83
Shubhank
  • 21,721
  • 8
  • 65
  • 83
  • Thank you. That did it. I had tried that in the past, but it didn't work then. Then again, I've corrected some logic mistakes since then. – drucifer Jan 24 '12 at 04:34
  • @itia Ferber thanks for editing my answer.. I was on my phone that's why lots of mistakes – Shubhank Jan 24 '12 at 04:42
0

rect1 does not contain rect2 in your example.

Rect 1 x coordinates span from 141 to 166. Rect 2 x coordinates span from 127 to 152.

Therefor, rect2 is not contained within rect1 (because rect2 exists within x coordinates 127-140, and rect1 does not exist in those coordinates).

Michael Frederick
  • 16,664
  • 3
  • 43
  • 58