
I have circles (there can be more than two) that are moving towards a point. As of now, they overlap when they are close. How can I make it so they do not intersect, but still move towards the point?
I am using Java.
- The circles are not balls that follow the laws of physics, they
represent organisms (irrelevant). - I already have collision detection working
- The circles do not stick together, they simply cannot intersect.
That’s not an easy question.
I presume you have some system which computes the coordinates of the circles, renders them, and repeats. These repetitions are called frames.
Each circle has a vector which describes the direction in which it is supposed to move. On each frame you need to perform collision detection, and change that vector if necessary.
Collision between any two circles can be detected by checking to see whether the distance between them is smaller than the sum of their radii. The line between the centers of the colliding circles gives you the direction of the collision. The collision vector for a circle is on the direction of the collision, pointing towards the center of the circle, and its magnitude is equal to half the number of units by which the circles overlap, that is, to the sum of their radii minus the distance between them, divided by two. (If the circles can be of unequal sizes it becomes more complicated, you need to figure out by how much to divide.)
So, one possible solution to your problem would be to simply add the collision vector to the direction vector of the circle and then scale the direction vector so that its magnitude is equal to the magnitude that it had before the collision. (So that only its direction will be adjusted, not its magnitude.)
Note that this will only work for the specific description that you gave, where you want the balls to stick together and continue moving towards the point; if you wanted a more realistic effect, you would need to emulate billiard balls type of physics.