keywords: Math, Ball, Move, Collision, Velocity

Question:
There're two balls in 3D world space, their radiuses are r1 and r2, their center locations are O1 and O2, and their constant velocity are V1 and V2, please detemine whether two balls collide with each other.

Solution:

  1. Assume that ball 1 is relative static to ball 2, so the relative velocity of ball 2 is V0 = V2 - V1.

  2. Then calculate the distance(named d) of O1(ball 1) and V0.

    Function 1 (In Unity):

     double ComputeDistance(vec3 O1, vec3 O2, vec3 V0) 
     {
         //dot project of V0 and a vector which starting from O2 to 01.
         float dotProj = (O1 - O2).Dot(V0);
    		
         //calculate cos value between V0 and (O1 - O2)
         double centerDist = O1.Distance(O2);
         double V0Len = V0.magnitude;
         double cos = dotProj / (centerDist * V0Len);
    		
         //length of centerDist projected on V0.
         double projectLen = centerDist * cos;
    		
         //perpendicular distance from O1 to V0.
         double d = Mathf.Sqrt(Mathf.Pow(centerDist) - Mathf.Pow(projectLen));
         return d;
     }
    

    Function 2 (In Unity):

     double computeDistance(vec3 O1, vec3 O2, vec3 V0) 
     {
         vec3 d = V0 / V0.magnitude;
         vec3 v = O1 - O2;
         double t = v.Dot(d);
         vec3 P = O2 + t * d;
         return P.Distance(A);
     }
    
  3. Two balls would collide with each other if d < r1 + r2.

Reference:
https://zhuanlan.zhihu.com/p/22614318


There is always something left to love. ― Gabriel García Márquez, <One Hundred Years of Solitude>