Search code examples
pythongeometrycollision-detection

Find if there is collision between two balls moving in a plane python


I have the following ball configuration:

P=(115,100)
T=(253,211)
C=(389,464)
r=60

enter image description here

The ball of center C and radius r follows a straight line from C to P.

In this trajectory there might be a ball T of radius r that causes a collision with ball C and deflects ball C from its course.

Ball of center T can be anywhere in the 2D plane except the blue region

Given C, T, P, and r, what is a clean and efficient way to detect whether or not ball T will interfer with ball C trajectory?

I would like to do this in python and other libraries can be used like numpy or pygame.


Solution

  • We can calculate distance D from point T to line CP.

    Define vector

    CP = P - C
    

    in coordinates:

    cpx = P.x - C.x
    cpy = P.y - C.y
    

    and normalize it

    length = math.hypot(cpx, cpy)
    ucpx = cpx / length
    ucpy = cpy / length
    

    Another vector

    CT = T - C
    ctx = T.x - C.x
    cty = T.y - C.y
    

    Distance using cross product

    D = abs(CT x UCP)
    D = abs(ctx*ucpy-cty*ucpx)
    

    One more value - sign of dot product of vectors allows to know if T lies "behind" C

    dtp =  (CT dot UCP)
    dtp =  (ctx*ucpx+cty*ucpy)
    

    Then compare D with radius sum (here doubled radius) and check sign of dot product

     if (D < 2*r) and (dtp > 0):
        collision occurs