C collision code between a rectangle and circle behaving incorrectly at high speeds of circle
09:38 10 Dec 2025

I have a function which handles collision between a rectangle and a circle, the rectangle is stationary, and the circle is moving towards the rectangle at some speed. When I input lower speeds then the behaviour is as expected but at a bit higher speed, my circle passes through the rectangle as if it didn't exist.

Here is a sketch of my collision algorithm, please assume that the rectangle is axis aligned:

My collision handling approach:

I figure out the point on the rectangle nearest to the position of my circle's centre, say this point is (Nx, Ny) and circle's radius is R and circle's centre is (Cx, Cy), then sufficient condition to check for a collision is (Nx-Cx)^2 + (Ny-Cy)^2 <= R^2 .

If collision has occurred then I can offset the position of the circle so that its not overlapping with the rectangle any more, as well as multiplying with -1 to the appropriate velocity component.

// All numerical values are type double
bool isCollision(Rectangle rec,Circle circ){
    Nx = clamp(circ.pos_x, rec.pos_x, rec.pos_x+rec.width);
    Ny = clamp(circ.pos_y, rec.pos_y, rec.pos_y+rec.height);
/* double clamp(v, min, max){
       if (v>=min && v<=max) return v;
       if (v < min)          return min;
       if (v > max)          return max;
   }
*/
    
// (Nx, Ny) gives me the coordinates of the point on rectangle nearest to the center of the circle.
    Dx = Nx - circ.pos_x;
    Dy = Ny - circ.pos_y;
    radius = circ.radius;
    if (Dx*Dx + Dy*Dy <= radius*radius){
        //Collision has occurred
        circ.velocity_x *= -1;
        circ.pos_x += (radius - abs(Dx))*(-1)*Dx/abs(Dx);
        // abs is absolute value, abs(4) = 4, abs(-3.9) = 3.9
        return true;
    } else{
        return false;
    }

}
c game-physics