我编写了一个python程序,其中一个圆从用户绘制的直线上弹开。有多个圆圈从墙上弹回。对于每一个球,应计算出距圆心和球的最短距离。我更希望这个代码是非常有效的,因为我目前的算法落后于计算机很多。如果a点是起点,b点是终点,c点是中心,r是半径,我怎么计算球之间的最短距离?如果球的X坐标超出AB段X坐标的范围,则该算法也可以工作
请发布python代码
任何帮助都将不胜感激!在
以下是我目前所掌握的情况:
lineList是一个包含4个值的列表,其中包含用户绘制的直线的起点和终点坐标
中心是球的中心
global lineList, numobjects
if not(0 in lineList):
beginCoord = [lineList[0],lineList[1]]
endCoord = [lineList[2]-500,lineList[3]-500]
center = [xCoordinate[i],yCoordinate[i]+15]
distance1 = math.sqrt((lineList[1] - center[1])**2 + (lineList[0] - center[0])**2)
slope1 = math.tan((lineList[1] - lineList[3]) / (lineList[0] - lineList[2]))
try:
slope2 = math.tan((center[1] - beginCoord[1])/(center[0]-beginCoord[0]))
angle1 = slope2 + slope1
circleDistance = distance1 * math.sin(angle1)
except:
#If the circle is directly above beginCoord
circleDistance = center[1] - lineList[1]
global numbounces
if circleDistance < 2 and circleDistance > -2:
print(circleDistance)
b = False
b2=False
if xCoordinate[i] < 0:
xCoordinate[i] += 1
speed1[i] *= -1
b=True
elif xCoordinate[i] > 0:
xCoordinate[i] -= 1
speed1[i] *= -1
b=True
if yCoordinate[i] < 0:
yCoordinate[i] += 1
speed2[i] *= -1
b2=True
elif yCoordinate[i] > 0:
yCoordinate[i] -= 1
speed2[i] *= -1
b2=True
if b and b2:
#Only delete the line if the ball reversed directions
numbounces += 1
#Add a ball after 5 bounces
if numbounces % 5 == 0 and numbounces != 0:
numobjects = 1
getData(numobjects)
canvas.delete("line")
lineList = [0,0,0,0]
我不知道球与球之间最短距离的平均值是多少,但如果你想计算圆与直线接触的点,你可以用sympy来计算公式:
输出为:
^{pr2}$这意味着您可以将垂直点计算为:
相关问题 更多 >
编程相关推荐