Point – Object Collision

After writing yesterday’s post, I noticed that I missed one big category of collisions: Point – Object collisions.  This is where a you check if a single XY pair is inside a object.  In this example I’ll use circles and squares, but you could use the algorithms that I wrote about in yesterday’s post with this method.

The technique is fairly simple.  For a square, all you have to do is check if the XY pair is inside a box.  The lua code looks like this:

function RectPoint(ax, ay, aw, ah, bx, by)
    return bx > ax and bx < ax + aw and by > ay and by < ay + ah 
end

All that this code does is checks if:

  1. the point’s X is greater then the rectangle’s X.
  2. The point’s X is less then the rectangle’s X + the rectangle’s width.
  3. the point’s Y is greater then the rectangle’s Y.
  4. the point’s Y is less then the rectangle’s Y + the rectangle’s height.

If these are all true, then it will return true, because the point is inside the rectangle.

The circle code is slightly more complex:

function CirclePoint(ax, ay, bx, by, ar)
    local dx = bx - ax
    local dy = by - ay
    local dist = math.sqrt(dx * dx + dy * dy)
    return dist < ar
end

This is essentially the same as the Distance Based Collision function that I wrote about in my previous post, except instead of taking 4 XY pairs and 2 radii, it takes 4 XY pairs and one radius, assuming that the other radius is zero.

For a example of these 2 functions in action, you can download the .love example file.  Feel free to use these functions in any way you wish.  If you want a license, use Creative Commons Zero.  If you have any questions, just comment, and I’ll try to help.

Advertisements

3 thoughts on “Point – Object Collision

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s