我正在 pygame 中编写游戏,我需要一个接受开始 (x1,y1) 和结束 (x2,y2) 作为参数的函数。使用pygame画线功能,我可以像这样从一个点到下一个点直线画一条线
def make_bullet_trail(x1,y1,x2,y2):
pygame.draw.line(screen,(0,0,0),(x1,y1),(x2,y2))
但是,我希望从 x1,y1 开始的线长度不超过 10 像素,因此如果点相距 100 像素,则不会绘制线的 90 像素。我怎样才能动态地编写这个代码,以便无论这 4 个点在哪里,这条线总是开始从一个点绘制到另一个点,并在十个像素后停止?
最佳答案
在调用画线函数之前,您可以调整您的 (x2, y2) 点。您可能想做这样的事情:
# Get the total length of the line
start_len = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# The desired length of the line is a maximum of 10
final_len = min(start_len, 10)
# figure out how much of the line you want to draw as a fraction
ratio = 1.0 * final_len / start_len
# Adjust your second point
x2 = x1 + (x2 - x1) * ratio
y2 = y1 + (y2 - y1) * ratio
由于您使用的是 pygame,因此您可能需要整数个像素。在这种情况下,您可能希望采用 int(round()) 来作为输出 x2 和 y2,并且您还希望调整比率,以便在主要(最长)中获得正好 10 个像素方向。要进行此调整,您只需使用 max(abs(x2-x1), abs(y2-y1))
作为长度即可。这不是真实的长度,但它将确保您每次绘制的像素数相同。
关于python - 如何绘制等长的动态线段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31757970/