I'm just trying to code a beautiful physical game.
A collision with a ball looks good, but if the balls collide too slowly, they βstickβ to each other. I donβt know why they do it.
Here is my collision function:
private void checkForCollision(ArrayList<Ball> balls) { for (int i = 0; i < balls.size(); i++) { Ball ball = balls.get(i); if (ball != this && ball.intersects(this)) { this.collide(ball, false); } } } public boolean intersects(Ball b) { double dx = Math.abs(b.posX - posX); double dy = Math.abs(b.posY - posY); double d = Math.sqrt(dx * dx + dy * dy); return d <= (radius + b.radius); } private void collide(Ball ball, boolean b) { double m1 = this.radius; double m2 = ball.radius; double v1 = this.motionX; double v2 = ball.motionX; double vx = (m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2); v1 = this.motionY; v2 = ball.motionY; double vy = (m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2); if (!b) ball.collide(this, true); System.out.println(vx + " " + vy); motionX = vx * BOUNCEOBJECT; motionY = vy * BOUNCEOBJECT; }
But this is what happens when they encounter low speed: 
Do you have an idea?
EDIT:
Alnitak's update works very well ... but one problem still exists ... if I add gravity as follows:
public void physic() { motionY += GRAVITY;
They are still moving into each other. I think this is the wrong way to add gravity, or is it not?
And I think I did something wrong with the collision formula, because they do not fall correctly:
! 
and then they slowly sink into the ground.
EDIT: found the AMAZING tutorial: http://www.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BouncingBalls.html
TeNnoX
source share