fred goodmasn
fred goodmasn

Reputation: 37

How to compare 2 distances in Python, Pygame with lines to create a box?

So what I want in theory is pretty simple. I want create something where you:

  1. have 2 lines that the user draws
  2. have code that take the first line and take the 2 points from it
  3. take the other lines 2 points
  4. takes the first point from the first line and compares it to the 2 points from (let's call it) line 2
  5. does the same for the 2nd point of line 1
  6. and draws line connecting the points the first point of line 1 to the closest point of line 2, then drawing the 2nd point of line one to the last one (of line 2).

Sounds a bit complicated, but probably because I'm bad a explaining things.

The code I have for this is here I also just want to add that the function "draw_line()" just takes the inputs of "start_pos", and "end_pos" so it doesn't matter what order the inputs are put in. Also "y2, y1" is the starting point or, 1st, and z is the 2nd.

def find_closer_point(self, origin_point, point1, point2):
# find the distance between both points and then choose the closest one to it
# the variables 
x2, x1 = origin_point
y2, y1 = point1
z2, z1 = point2
# the distance formula
calc1 = ((x2 - x1) ^ 2) + ((y2 - y1) ^ 2)
calc2 = ((x2 - x1) ^ 2) + ((z2 - z1) ^ 2)
# to compare the distances (which seems to be the hard part)
try:
    if math.sqrt(calc1) > math.sqrt(calc2):
        self.draw_line((x2, x1), (z2, z1))
except ValueError:
    new_calc1 = math.sqrt(abs(calc1))
    new_calc2 = math.sqrt(abs(calc2))
    if new_calc1 > new_calc2:
        self.draw_line((x2, x1), (z2, z1))
    if new_calc1 < new_calc2:
        self.draw_line((x2, x1), (y2, y1))

I can't seem to find what's wrong. Also, if I need to provide more code as context or if something else is wrong then just ask.

Upvotes: 1

Views: 118

Answers (1)

Rabbid76
Rabbid76

Reputation: 210890

Use the Dot product to find the point with the pointe which is "nearer" in a certain direction

def dot(p1, p2):
    return p1[0]*p2[0] + p1[1]*p2[1]
if dot(origin_point, point1) < dot(origin_point, point2):
    self.draw_line(origin_point, point1)
else:
    self.draw_line(origin_point, point2)

The Dot product of 2 vectors is equal the cosine of the angle between the 2 vectors multiplied by the magnitude (length) of both vectors.

dot(A, B) == | A | * | B | * cos(angle_A_B)

This follows, that the dot product of 2 unit vectors is equal the cosine of the angle between the 2 vectors, because the length of a unit vector is 1.

uA = normalize(A)
uB = normalize(B)
cos(angle_A_B) == dot(uA, uB)

Upvotes: 1

Related Questions