Search code examples
matlablogic2dcollision-detectionphysics

2D Circle-Circle Collision Strange Behavior


Hello StackOverflow community! I'm working in a problem with circles collision. To put it in simple terms, all collisions are ideal elastic. The balls can only move in diagonals. So this sounds pretty simple. Now, for some reason with my current code, which I'll attach below, the balls "stick" to each other instead of colliding. I think what's happening is they are constantly "swapping their velocities" and that's why they can't get apart, but I might be wrong.

[code removed]


Solution

  • I would add another ifcondition after if dist <= (2 * radius) to check if they are moving towards each other or away from each other by predicting the distance between them after the next move and comparing with the current distance.

    dist_next = sqrt( ((x(i)+velocity_x(i)) - (x(j)+velocity_x(j))^2 + ((y(i)+velocity_y(i)) - (y(j)+velocity_y(j)))^2 );
    
    if dist_next < dist
    ...
    end
    

    I hope I got all the parenthesis right...