First of all in order to calculate the collision detection between a sphere(circle in 2D) and a line you need to calculate the perpendicular vector between the moving ball's center and the line, in order to calculate this distance you need to do the following:
So in order to calculate d in the above figure we need to do some steps.
- Assume your line is using the parametric equation P(t) = S + t V note that V is the line direction can be obtained by subtracting (P2 - P1).
- From Pythagoras:
d^2 = len(Q - S)^2 - len( proj(Q - S ) )^2
Then you expand the equation to get the following, it seems a bit complicated but it's actually not.
d = sqrt( len(Q - S)^2 - len( (Q - S) dot V )^2 / V^2 )
Where Q is the circle's center and S is any point on the line. Once the distance is less than the circle/sphere radius you need to trigger collision response which is explained in the next point.
It's incorrect to always flip the x or y component to bounce the ball, what you need to do is to reflect the velocity vector, in order to do so you need to calculate the Normal vector of the surface and use that normal for calculating the reflection vector using the following equation
R = 2 * (V dot N)* N - V
where R is the reflection vector, N is the normal of the surface and V is the Velocity vector.
In case of 45 deg your surface normal will be N = (1,1,0) with varying sign depending on which direction the normal faces (position or negative).