2
\$\begingroup\$

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?

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

1 Answer 1

0
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.