I have the following situation:

To detect whether is the red rectangle is inside orange area I use this function:

- (BOOL)isTile:(CGPoint)tile insideCustomAreaMin:(CGPoint)min max:(CGPoint)max {
    if ((tile.x < min.x) ||
        (tile.x > max.x) ||
        (tile.y < min.y) ||
        (tile.y > max.y)) {
        NSLog(@" Object is out of custom area! ");
        return NO;
    return YES;

But what if I need to detect whether the red tile is inside of the blue rectangle? I wrote this function which uses the world position:

- (BOOL)isTileInsidePlayableArea:(CGPoint)tile {

    // get world positions from tiles
    CGPoint rt = [[CoordinateFunctions shared] worldFromTile:ccp(24, 0)];
    CGPoint lb = [[CoordinateFunctions shared] worldFromTile:ccp(24, 48)];
    CGPoint worldTile = [[CoordinateFunctions shared] worldFromTile:tile];

    return [self isTile:worldTile insideCustomAreaMin:ccp(lb.x, lb.y) max:ccp(rt.x, rt.y)];

How could I do this without converting to the global position of the tiles?

  • \$\begingroup\$ insideCustomAreaMin will work only for axis aligned rectangles. To hit-test against blue rect you need a fair hit-test function. \$\endgroup\$ – Kromster Aug 21 '14 at 10:51
  • \$\begingroup\$ Sorry for my question, but what is "fair hit-test func" ? \$\endgroup\$ – gronzzz Aug 21 '14 at 18:40
  • \$\begingroup\$ I believe that @KromStern is simply referring to a decent Hit-testing implementation. \$\endgroup\$ – Joshua Drake Aug 21 '14 at 19:45
  • \$\begingroup\$ The top 3 results for 2d collision detection may be helpful. \$\endgroup\$ – Joshua Drake Aug 21 '14 at 19:48

Rectangles are convex polygons which makes this very easy.

To test whether a point lies within a convex polygon, check that it lies on the same "side" of all the edges of the polygon. Sketch this out to see how this is only possible if the point is inside. Here's the SO question for this: https://stackoverflow.com/questions/1119627/how-to-test-if-a-point-is-inside-of-a-convex-polygon-in-2d-integer-coordinates

To test whether a convex polygon lies within another convex polygon, simply perform the same point-inside-polygon test but repeat it for all the points of the first polygon.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.