如何使用python查找投射物运动的范围?

2024-05-14 04:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python模拟多角度的弹丸运动。这是一个几乎完成的代码,除了我还需要显示每个射弹的射程。你知道我该怎么做吗

import numpy as np 
import matplotlib.pyplot as plt 
import math 

#theta=pi/3
V=38.5 #speed
t=np.arange(0,19,0.1)

angle = math.pi/12
angle_list=[]

while angle < math.pi/2:
    x=V*np.cos(angle)*t
    y=V*np.sin(angle)*t+(0.5*-9.8*t**2)
    plt.ylim([0,80])
    plt.xlim([0,170])
    print(x,y)
    plt.plot(x,y)
    angle_list.append(rf'{np.rad2deg(angle):.0f}$\degree$')
    angle+=math.pi/12
    

plt.xlabel("range")
plt.ylabel("height")
plt.title('Projectile Motion With Multiple Angles')
plt.legend(angle_list)
plt.show()

图表的图片:

enter image description here


Tags: 代码importnumpymatplotlibasnppiplt
1条回答
网友
1楼 · 发布于 2024-05-14 04:22:38

您只需要找到零交叉点,即x的最大值,该值为y > 0,并提供可用于注释图形的范围,如下所示-

import numpy as np
import matplotlib.pyplot as plt
import math

# theta=pi/3
V = 38.5  # speed
t = np.arange(0, 19, 0.1)

angle = math.pi / 12
angle_list = []

while angle < math.pi / 2:
    x = V * np.cos(angle) * t
    y = V * np.sin(angle) * t + (0.5 * -9.8 * t ** 2)
    plt.ylim(0, 80)
    plt.xlim(0, 170)
    # print(x, y)
    plt.plot(x, y)
    zero_crossing_idx = np.argwhere(y > 0)[-1]
    plt.annotate('{:.2f}'.format(x[zero_crossing_idx][0]), (x[zero_crossing_idx//2], y[zero_crossing_idx//2]+0.5))
    angle_list.append(rf'{np.rad2deg(angle):.0f}$\degree$')
    angle += math.pi / 12

plt.xlabel("range")
plt.ylabel("height")
plt.title('Projectile Motion With Multiple Angles')
plt.legend(angle_list)
plt.show()

enter image description here

相关问题 更多 >