Tuesday, January 27, 2015

Circle to Rectangle Collision

I was messing around with some twin-stick shooter stuff one day and after creating the first enemy I wanted to add some collision between the player character's bullets and the enemy. The bullets and the enemy are both circles and FlashPunk doesn't have circle collision functions built in so I decided to make one for myself. Turns out circle to circle collision is pretty simple. If you imagine a line from the center of one circle to the center of the other circle, then you just check if the length of that line is less than or equal to the two circle's radii.

if (FP.distance(c1X, c1Y, c2X, c2Y) - (c1Radius + c2Radius) <= 0) return true;





But then I wanted a collision check between a circle and a rectangle. After some problem solving in my head and looking at it visually with some Draw objects, I couldn't figure it out and gave up. Last night, however, I was thinking about it while trying to fall asleep and realized there are just two common points where a circle and rectangle will collide. One would be one of the corners of the rectangle and the other would be one of the 90 degree points on the circle's circumference.

Today I'm trying to build a function around this idea. My thought process starts at the end; taking two points, one on the circle and one on the square, and then calculating the distance between them. The first step in the function would be if the distance is from a rectangle corner or from a circle cross-hair line. Then just take the two points and the edge of each object to calculate the distance.



No comments:

Post a Comment