Simple 2D collision algorithms
From GDWiki
- This article is a stub. You can help out by expanding it.
Sometimes, it is necessary to have formulas for 2D collision detection, and sometimes we do not know how to do the checking. Here follows some basic algorithms for checking whether simple 2D primitives collide or not.
Contents |
[edit] Point collisions
[edit] Point in triangle
// The names t1x, t3y, etc refer to the triangle corners' x and y values // t1x being the first corner's x value and so on. // px/py means the point'sx and y values function PointInTriangle(t1x, t1y, t2x, t2y, t3x, t3y, px, py) // absolute means the positive version of a number. Ex: // absolute(-5) = 5 // absolute(5) = 5 a1 = absolute((t2x-t1x) * (t3y-t1y) - (t3x-t1x) * (t2y-t1y)) a2 = absolute((t1x-px) * (t2y-py) - (t2x-px) * (t1y-py)) a3 = absolute((t2x-px) * (t3y-py) - (t3x-px) * (t2y-py)) a4 = absolute((t3x-px) * (t1y-py) - (t1x-px) * (t3y-py)) result = absolute(a2+a3+a4-a1) if result <= 1/256 return true else return false end
[edit] Point in rectangle
// rx/ry defines the rectangle's x/y coordinates // rw/rh defines the rectangle's width and height, respectively function PointInRectangle(rx, ry, rw, rh, px, py) if px < rx return false if px > rx+rw return false if py < ry return false if py > ry+rh return false return true end
[edit] Point in circle
// cx/cy = the center of the circle, x and y coordinates // r = radius of the circle // px/py = the point's x and y coordinates function PointInCircle(cx, cy, r, px, py) if(((px-cx)*(px-cx) + (py-cy)*(py-cy)) <= r*r) return true return false end
Note: It is a lot faster without using sqrt. Instead we just use r*r and no sqrt on the other side.
[edit] Circle collisions
[edit] Circle in circle
// c1x/c1y is the first circle's x/y coordinates // c1r is the first circle's radius // The same applies to the other parameters, only that it's the second circle function CircleInCircle(c1x, c1y, c1r, c2x, c2y, c2r) if(sqr((c2x-c1x)*(c2x-c1x) + (c2y-c1y)*(c2y-c1y)) <= c1r+c2r) return true return false end
[edit] Circle in rectangle
[edit] Rectangle collisions
[edit] Rectangle in rectangle
// r1x/r1y is the first rectangle's x and y position // r1w/r1h is the first rectangle's width and height // r2x/r2y/r2w/r2h follow the same principle, but apply to the second rectangle function RectangleInRectangle(r1x, r1y, r1w, r1h, r2x, r2y, r2w, r2h) if r1x+r1w < r2x return false if r1x > r2x+r2w return false if r1y+r1h < r2y return false if r1y > r2y+r2h return false return true end

