home made func

This commit is contained in:
2019-10-10 17:47:35 +02:00
parent 8aa660d12d
commit 04222b6148
2 changed files with 27 additions and 22 deletions

View File

@@ -106,7 +106,7 @@ class Car(pygame.sprite.Sprite):
for i,s in enumerate(self.sensors) : for i,s in enumerate(self.sensors) :
ip = segments_intersection(s,l) ip = segments_intersection(s,l)
print(s, l) print(s, l)
if ip is not None : if ip :
# print("ip", ip) # print("ip", ip)
d = distance(ip, self.left_sensor[1]) d = distance(ip, self.left_sensor[1])
# print('d',d) # print('d',d)
@@ -137,7 +137,7 @@ all_cars.add(car2)
ip = segments_intersection(car2.center_sensor, car2.left_sensor) ip = segments_intersection(car2.center_sensor, car2.left_sensor)
print(ip) print(ip)
print(math.hypot(ip[0] - car2.rect.center[0], ip[1] - car2.rect.center[1])) # print(math.hypot(ip[0] - car2.rect.center[0], ip[1] - car2.rect.center[1]))
# stress test # stress test
# for x in range(100): # for x in range(100):
@@ -175,4 +175,4 @@ while True :
for line in lines : for line in lines :
pygame.draw.line(screen, (255,255,255), line[0], line[1]) pygame.draw.line(screen, (255,255,255), line[0], line[1])
pygame.display.flip() pygame.display.flip()
clock.tick(2) clock.tick(10)

View File

@@ -6,30 +6,35 @@ def angle_to_vector(angle):
return [math.cos(angle), math.sin(angle)] return [math.cos(angle), math.sin(angle)]
def get_line_feats(point1, point2):
x1,y1 = point1
x2,y2 = point2
a = (y1-y2)/(x1-x2)
b = y2 - a * x2
return a,b
def segments_intersection(line1, line2): def segments_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) p1,p2 = line1
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) p3,p4 = line2
def det(a, b): a1,b1 = get_line_feats(p1,p2)
return a[0] * b[1] - a[1] * b[0] a2,b2 = get_line_feats(p3,p4)
div = det(xdiff, ydiff) if a1==a2 :
if div == 0: return None # parrallel lines
return None
x = (b2-b1)/(a1-a2)
if min(p1[0], p2[0]) <= x <= max (p1[0], p2[0]) and min(p3[0], p4[0]) <= x <= max (p3[0], p4[0]) :
y = a1 * x + b1
return x,y
else :
return None # intersect is outside segments
d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
if (
min(line1[0][0],line1[1][0]) <= x <= max(line1[0][0],line1[1][0])
and min(line2[0][0],line2[1][0]) <= x <= max(line2[0][0],line2[1][0])
and min(line1[0][1],line1[1][1]) <= y <= max(line1[0][1],line1[1][1])
and min(line2[0][1],line2[1][1]) <= y <= max(line2[0][1],line2[1][1])
):
return x, y
return x, y
def distance(point1, point2): def distance(point1, point2):
return math.hypot(point1[0] - point2[0], point1[1] - point2[1]) return math.hypot(point1[0] - point2[0], point1[1] - point2[1])