Point In Rect

Discuss new features and future development.

Point In Rect

Postby shafijami » Fri Dec 19, 2008 5:16 am


Is there any version of PointInRect like in chipmunk. How do we know if a ball is inside a rectangle or another shape?

Posts: 4
Joined: Fri Dec 12, 2008 6:53 am

Re: Point In Rect

Postby Ostsol » Sat Jan 17, 2009 6:31 pm

Assume you have a rectangle defined in a clockwise manner with points a, b, c, and d. Point a is at the upper left. This gives you four edges, which we will lable ab, bc, cd, and da. If we drew this on a sheet of paper and and looked at the top edge, ab, anything above the edge is obviously outside the rectangle and a point below might be inside the rectangle. Rotate the paper such that edge bc is horizontal, with point b being to the left of point c. Once again, anything above that edge is always outside the rectangle and a point below the edge might be inside. Rotate the paper again such that cd is horizontal, with point c left of d. The same above/below rules will apply. Thus, a point can only be inside the rectangle if it is "below" all edges.

Here's some pseudo-code to tell you if a point is "above" or "below" a line:

e1 = p2 - p1
e2 = point - p2

e = e1.x * e2.y - e1.y * e2.x
if e > 0 then above
if e < 0 then below
if e == 0 then on_line

"p1" and "p2" are the two points (as 2d vectors) of the edge being tested. "point" is the point being tested.

This works on any convex polygon as long as the points are arranged in a clockwise manner. A polygon that is not fully convex must be divided into convex polygons.
Posts: 12
Joined: Sat Jan 26, 2008 9:16 pm

Re: Point In Rect

Postby slembcke » Sat Jan 17, 2009 11:47 pm

Added in 4.1.0. Works for any Chipmunk shape type:
Code: Select all
int cpShapePointQuery(cpShape *shape, cpVect p)

You may also want to check out:
Code: Select all
typedef void (*cpSpacePointQueryFunc)(cpShape *shape, void *data);
void cpSpaceShapePointQuery(cpSpace *space, cpVect point, cpSpacePointQueryFunc func, void *data);
void cpSpaceStaticShapePointQuery(cpSpace *space, cpVect point, cpSpacePointQueryFunc func, void *data);

These functions are accelerated by the spatial hash and will be much faster than checking each shape individually.
Can't sleep... Chipmunks will eat me...
Check out our latest projects! -> http://howlingmoonsoftware.com/wordpress/
User avatar
Site Admin
Posts: 4164
Joined: Tue Aug 14, 2007 7:13 pm

Return to Features/Development

Who is online

Users browsing this forum: No registered users and 2 guests