【问题标题】:how to draw dynamic line segments of the same length如何绘制相同长度的动态线段
【发布时间】:2015-08-01 03:43:08
【问题描述】:

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

【问题讨论】:

    标签: python pygame graphing


    【解决方案1】:

    在调用画线函数之前,你可以调整你的 (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)) 作为长度。这不是真正的长度,但它可以确保您每次绘制的像素数相同。

    【讨论】:

      猜你喜欢
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多