| 
9 | 9 | import math  | 
10 | 10 | import matplotlib.pyplot as plt  | 
11 | 11 | 
 
  | 
 | 12 | +old_nearest_point_index = None  | 
 | 13 | + | 
12 | 14 | k = 0.1  # look forward gain  | 
13 | 15 | Lfc = 1.0  # look-ahead distance  | 
14 | 16 | Kp = 1.0  # speed proportional gain  | 
@@ -71,14 +73,31 @@ def pure_pursuit_control(state, cx, cy, pind):  | 
71 | 73 | 
 
  | 
72 | 74 |     return delta, ind  | 
73 | 75 | 
 
  | 
 | 76 | +def calc_distance(state, point_x, point_y):  | 
 | 77 | +    dx = state.rear_x - point_x  | 
 | 78 | +    dy = state.rear_y - point_y  | 
 | 79 | +    return math.sqrt(distance_x ** 2 + distance_y ** 2)  | 
 | 80 | + | 
74 | 81 | 
 
  | 
75 | 82 | def calc_target_index(state, cx, cy):  | 
76 | 83 | 
 
  | 
77 |  | -    # search nearest point index  | 
78 |  | -    dx = [state.rear_x - icx for icx in cx]  | 
79 |  | -    dy = [state.rear_y - icy for icy in cy]  | 
80 |  | -    d = [abs(math.sqrt(idx ** 2 + idy ** 2)) for (idx, idy) in zip(dx, dy)]  | 
81 |  | -    ind = d.index(min(d))  | 
 | 84 | +    if old_nearest_point_index is None:  | 
 | 85 | +        # search nearest point index  | 
 | 86 | +        dx = [state.rear_x - icx for icx in cx]  | 
 | 87 | +        dy = [state.rear_y - icy for icy in cy]  | 
 | 88 | +        d = [abs(math.sqrt(idx ** 2 + idy ** 2)) for (idx, idy) in zip(dx, dy)]  | 
 | 89 | +        ind = d.index(min(d))  | 
 | 90 | +    else:  | 
 | 91 | +        index = old_nearest_point_index  | 
 | 92 | +        distance_this_index = calc_distance(state, cx[index], cy[index])  | 
 | 93 | +        while True:  | 
 | 94 | +            index = index + 1 if (index + 1) < len(cx) else index  | 
 | 95 | +            distance_next_index = calc_distance(state, cx[index], cy[index])  | 
 | 96 | +            if distance_this_index < distance_next_index  | 
 | 97 | +                break  | 
 | 98 | +            distance_this_index = distance_next_index  | 
 | 99 | +        old_nearest_point_index = index  | 
 | 100 | + | 
82 | 101 |     L = 0.0  | 
83 | 102 | 
 
  | 
84 | 103 |     Lf = k * state.v + Lfc  | 
 | 
0 commit comments