如何绘制等长的动态线段

how to draw dynamic line segments of the same length

我正在 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 个点在哪里,线总是从一个点开始绘制到另一个点,并在 10 个像素后停止?

在你调用画线函数之前,你可以调整你的(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,您可能需要整数像素。在这种情况下,您可能希望对输出 x2 和 y2 使用 int(round()),并且您还希望调整比率,以便在主要(最长)方向上恰好获得 10 个像素。要进行此调整,您可以简单地使用 max(abs(x2-x1), abs(y2-y1)) 作为长度。这不是实际长度,但可以确保每次绘制的像素数相同。