Rounding error accumulation and workaround. Collision detection.

32 Views Asked by At

I do not know, fellows, how best to describe my problem. But I will try my best. I think this question is more for mathematicians than programmers.

There is 2 objects (fig.1): One object is a wall (indicated in black) And the other is a deformable object in the form of a line segment (blue). Object coordinates are represented as integers.

At some point, I split the line in half, calculating the midpoint C = [55.5, 39.5]. When the midpoint is calculated and its coordinates are rounded (C_rounded=[56, 40]), we see that the two new lines no longer form a straight line. And the new line segment collides with the wall.

To get around this problem, I had to take into account several aspects:

  1. In fact, a straight line is not represented by a set of points lying on one straight line, but by a set of points located within a radius of R from a mathematically defined line (fig.2)
  2. By trial and error, I found out that R = 2 units (2*minimum integer = 2 * 1 = 2). I could be wrong.

Therefore, I need to find a straight line segment that lies "above" and not very far away from the range of points. The length of this segment is equal to the initial length of the line + 2 * R (Fig.2)

What I want to do and where I need help is to find some function, if mathematically possible, that calculates the line segment that is "above" the entire range of "line" points. If I insert line segment endpoints into this function, I should get a line segment that is "above" the entire range of the current line segment.

Function(A, B) = Line_AB
Function (A, C) = Line_AC ( this line is 'below' Line_AB)

Programmatically, I found a solution, but it works slowly due to recursion (loop), and when the slope is close to 45 degrees, the distance from the initial segment is too large (Fig.3)

Pseudocode (Fig.3):

  • Calculate the midpoint
  • Round off the coordinates of the midpoint
  • Draw 2 right-angled triangles
  • Connect two points of the triangles - we get the desired line

Fig.1

Fig.2

Fig.3