0
\$\begingroup\$

I have a bouncing ball which can collide with lines of a random slope. The ball passes through the lines a bit and I need to set the ball back some distance from the line.

The ball (defined by position and radius) travels according to a speed vector (obtained by multiplying a direction vector by a magnitude) and I want to find the distance between the center and the line so I know how many pixels the ball passed through the line.

enter image description here

In the example the ball passed 10 pixels (radius - dist) after the line, I need to move the center of the ball 10 pixels in the opposite direction.

How can I those pixels between x and y so I can subtract them from the center coordinates?

Thanks

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

What you need is the vector of the shortest distance between the Wall and the balls center. More generally, you seek the distance between a point and a line.

Paul Bourke has given a general solution to this well known geometry Problem on his website:

This note describes the technique and gives the solution to finding the shortest distance from a point to a line or line segment. The equation of a line defined through two points P1 (x1,y1) and P2 (x2,y2) is P = P1 + u (P2 - P1)

The point P3 (x3,y3) is closest to the line at the tangent to the line which passes through P3, that is, the dot product of the tangent and line is 0, thus (P3 - P) dot (P2 - P1) = 0

Substituting the equation of the line gives

[P3 - P1 - u(P2 - P1)] dot (P2 - P1) = 0

Solving this gives the value of u

Substituting this into the equation of the line gives the point of intersection (x,y) of the tangent as

x = x1 + u (x2 - x1)

y = y1 + u (y2 - y1)

The distance therefore between the point P3 and the line is the distance between (x,y) above and P3.

Notes

  • The only special testing for a software implementation is to ensure that P1 and P2 are not coincident (denominator in the equation for u is 0)

  • If the distance of the point to a line segment is required then it is only necessary to test that u lies between 0 and 1.

  • The solution is similar in higher dimensions.

With the distance now calculated as (x,y) and the center of your ball as (cx,cy),

new_cx = cx - (radius-x)

and

new_cyy = cy - (radius -y);

On a side node, very fast moving balls might not intersect with the wall if they move more than the balls diameter per frame, since they might then "skip" through the wall, being in front of it in one fraem and completely behind behind it in the next.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .