首页 > 解决方案 > 如何在pygame中绘制动态箭头?

问题描述

我尝试使用pg.draw.arrow(),但显然不存在。我想创建一个箭头,其中末端根据线的旋转进行更新,以便它们始终对齐。这可能吗?

标签: pythonpygame

解决方案


我一直在使用这个函数,有点基于我不久前在 stackoverflow 上看到的内容:

def arrow(screen, lcolor, tricolor, start, end, trirad, thickness=2):
    pg.draw.line(screen, lcolor, start, end, thickness)
    rotation = (math.atan2(start[1] - end[1], end[0] - start[0])) + math.pi/2
    pg.draw.polygon(screen, tricolor, ((end[0] + trirad * math.sin(rotation),
                                        end[1] + trirad * math.cos(rotation)),
                                       (end[0] + trirad * math.sin(rotation - 120*rad),
                                        end[1] + trirad * math.cos(rotation - 120*rad)),
                                       (end[0] + trirad * math.sin(rotation + 120*rad),
                                        end[1] + trirad * math.cos(rotation + 120*rad))))

我定义rad为 pi/180 将度数转换为弧度

如果要将其分配给draw

setattr(pg.draw, 'arrow', arrow)

推荐阅读