Search code examples
geometrycollision

Calculate the position of moving circle when it touches a rectangle



i have the following Situation: A circle is moving linear towards a non-moving Rectangle. Is there an efficient way to calculate the position of the circle when it touches the Rectangle?

I need this to handle collisions. The circles should move as close as possible to the rectangle instead of just simply stop moving, if the movement would cause intersection. I was able solve the problem with a Circle moving towards another Circle, since you can just use the moving equation plus the radiuses. But with rectangles i have at the moment no clue how to calculate it (efficiently) without a binary-search along the path of the circle.


Solution

  • To solve this problem, you can imagine that the circle deflates to a single point while the rectangle inflates and turns to a rectangle with rounded corners. Now you have to intersect the trajectory of the center with that shape.

    enter image description here

    Now you need to check if the ray intersects a straight edge of the inflated rectangle (which is easy, check if the endpoints are on either sides), or one of the arcs at corners (which is less easy: by using the parametric equation of the ray and the implicit equation of the circles, you get quadratic equations, and you must eliminate the solutions that are not in the right quadrant).

    This takes a little of analytical geometry but is quite manageable. Notice that this tells you the position of the center when there is contact, but by continuing on a length R along the ray, you get the contact point.