闪电轨迹本身就是有棱有角的,不能太平滑,也不能有奇怪的凸起。
写了个代码发现生成的不太像,倒像是一个国家的边境线了。
其中17 18行的代码是用来做随机偏移的,可以调整这4个参数以及35行的终止距离。
[Python] 纯文本查看 复制代码import matplotlib.pyplot as plt
import random
def generate_lightning(start_point, end_point, max_distance):
points = [start_point, end_point]
while True:
all_within_max_distance = True
new_points = []
for i in range(len(points) - 1):
p1 = points[i]
p2 = points[i + 1]
distance = ((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) ** 0.5
if distance > max_distance:
all_within_max_distance = False
midpoint = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
offset_x = random.uniform(-distance / 12, distance / 4)
offset_y = random.uniform(-distance / 6, distance / 6)
new_midpoint = (midpoint[0] + offset_x, midpoint[1] + offset_y)
new_points.extend([p1, new_midpoint])
else:
new_points.append(p1)
new_points.append(points[-1])
points = new_points
if all_within_max_distance:
break
return points
# 设置起始点和终点坐标以及最大距离
start_point = (0, 0)
end_point = (100, 100)
max_distance = 8
# 生成闪电轨迹的点列表
lightning_points = generate_lightning(start_point, end_point, max_distance)
# 绘制闪电
x_coords, y_coords = zip(*lightning_points)
plt.plot(x_coords, y_coords, 'b-')
# 设置图形的坐标轴范围等
plt.xlim(min(x_coords) - 1, max(x_coords) + 1)
plt.ylim(min(y_coords) - 1, max(y_coords) + 1)
# 显示图形
plt.show()