Search code examples
c#algorithmunity-game-enginecollision-detection

Fastest way to check balls that will be hit in a segment


There are N red balls and a white ball, all with the same radius. The white ball moves from position p1 to p2.

My objective is to predict all red balls the white ball will hit in its path and turn them yellow.

I tried iterating through all balls and taking the distance to the line formed by p1 and p2, but the balls that are behind the white turned yellow too, but they shouldn't. How should I approach this task? Is there a fast way to do it?

You can suppose that the white follows its path ignoring all collisions, the only objective is to predict what balls are in its way.

enter image description here


Solution

  • You should color the balls whose centres lie within this rectangle:

    enter image description here

    The short sides of that rectangle are perpendicular to the line through P1-P2, going through the centres of P1 and P2 respectively. Their length is 4 x radius, with P1/P2 at the middle of the line segment.

    The long sides are parallel with the line through P1-P2.

    Now you only need to check whether a red ball's centre point is on the right side of each of these four lines.

    Check "How to tell whether a point is to the right or left side of a line?" on how you can do that.