0
\$\begingroup\$

I have a ball (with parameters x, y, radius) that travels on the screen (with vectors directionX directionY) and can collide with a segment with random slope (with parameters startX, startY, stopX, stopY).

https://scontent-a-mad.xx.fbcdn.net/hphotos-xaf1/v/t1.0-9/10320317_10205547836036948_1009384364939997889_n.jpg?oh=5d20edaab20032d5babfcf419d02f061&oe=556C42B3

After i detect the collision i split code for calculate bounce vector in two different situations: first situation is ball in the middle of the segment (which is now working properly) and second is ball colliding the segment corners (starting or ending point) of a segment. Now,my algorythm is more or less working but sometimes there is some wrong behaviour and bounce is wrong or even no bounce (ball pass through the line without bounce)

This is the code i'm currently using:

       if (Math.pow(line.startX - x, 2) + Math.pow(line.startY - y, 2) <= Math.pow(radius, 2) || Math.pow(line.stopX - x, 2) + Math.pow(line.stopY - y, 2) <= Math.pow(radius, 2)) {
          // ball has hit the corner of the segment
           if (Math.pow(line.startX - x, 2) + Math.pow(line.startY - y, 2) <= Math.pow(radius, 2)){
               //calculate bounce vector with starting point of segment
                float x1 = x - line.startX;
                float y1 = y - line.startY;
                float c1 = (float) (-2 * (directionX * x1 + directionY * y1) / (x1 * x1 + y1 * y1));
                directionX += c1 * x1;
                directionY += c1 * y1;

           }
           else{
               //calculate bounce vector with ending point of segment
                float x1 = x - line.stopX;
                float y1 = y - line.stopY;
                float c1 = (float) (-2 * (directionX * x1 + directionY * y1) / (x1 * x1 + y1 * y1));
                directionX +=  c1 * x1;
                directionY +=  c1 * y1;
           }
        }   

      else
            {
 //other code for calculating bounce vector after collision inside segment.

}

\$\endgroup\$
1
\$\begingroup\$

You need to change the collision of a ball against an infinitely thin line to an infinitely small point (ray) against a thick segment with two round ends

You transfer the ball's thickness to the segment. Both end points become circles.

The collision then becomes a 2D ray-cast operation.

enter image description here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.