These 4 conditions appear to concern themselves with detecting a collision
if (x_pos1 == x_pos2 + 40) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
if (x_pos2 == x_pos1 ) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
if (x_pos1 + 40 == x_pos2) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
if (x_pos2 + 40 == x_pos1) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
But they all ask if objects are at exact positions relative to other objects rather than within a range. Remember because this sort of program runs in time jumps an object may be partially within annother when the collision occurs, Changing all 4 of these conditions to just this one condition solves the problem
if (Math.abs(x_pos2-x_pos1)<radius1+radius2){
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
This rather than asking if the balls at specific distances from each other asks if then are overlapping at all, which provides a much safer test.
Obviously you know that these simple reverse velocity collisions are not physically correct, but an additional thing to watch out for is if a collision occurs in an overlap and (for whatever reason) the two objects aren't brought out of collision in the next time step, then annother collision occures, once this happens the two balls seem to "stick together". This can be resolved by physically moving the objects out of collision, then applying the velocity changes. This problem happens a lot with non elastic collisions but can also occure when multiple bodies collide at the same time.