在PyGame中绘制符合线条方向的箭头

问题描述 投票:4回答:3

在Pygame中,如果给定箭头的起点和终点,我如何计算箭头的三个点的坐标,以便箭头指向与线相同的方向?

def __draw_arrow(self, screen, colour, start, end):     
    start = self.__coordinate_lookup[start]
    end = self.__coordinate_lookup[end]
    dX = start[0] - end[0]
    dY = -(start[1] - end[1])
    print m.degrees(m.atan(dX/dY)) + 360 
    pygame.draw.line(screen,colour,start,end,2)

我已经尝试过使用角度和线条的渐变,Y坐标向下而不是向上增加的事实让我失望,我真的很感激在正确的方向上轻推。

python python-2.7 pygame geometry algebra
3个回答
3
投票

这应该工作:

def draw_arrow(screen, colour, start, end):
    pygame.draw.line(screen,colour,start,end,2)
    rotation = math.degrees(math.atan2(start[1]-end[1], end[0]-start[0]))+90
    pygame.draw.polygon(screen, (255, 0, 0), ((end[0]+20*math.sin(math.radians(rotation)), end[1]+20*math.cos(math.radians(rotation))), (end[0]+20*math.sin(math.radians(rotation-120)), end[1]+20*math.cos(math.radians(rotation-120))), (end[0]+20*math.sin(math.radians(rotation+120)), end[1]+20*math.cos(math.radians(rotation+120)))))

对不起,组织不良的代码。但正如你所说,从左上角开始的坐标需要翻转一些数学运算。此外,如果你想将三角形​​从等边距更改为其他东西,你只需要更改第4行中的rotation +/- 120,或者更改半径不同的20*

希望这可以帮助 :)


2
投票

我将起点和终点坐标表示为startX, startY, endX, endY enter image description here

dX = endX - startX
dY = endY - startY

//vector length 
Len = Sqrt(dX* dX + dY * dY)  //use Hypot if available

//normalized direction vector components
udX = dX / Len
udY = dY / Len

//perpendicular vector
perpX = -udY
perpY = udX

//points forming arrowhead
//with length L and half-width H
arrowend  = (end) 

leftX = endX - L * udX + H * perpX
leftY = endY - L * udY + H * perpY

rightX = endX - L * udX - H * perpX
rightY = endY - L * udY - H * perpY

0
投票

弗拉基米尔的答案很棒!对于将来访问的任何人来说,这里的功能是控制箭头的每个方面:

def arrow(screen, lcolor, tricolor, start, end, trirad):
    pg.draw.line(screen,lcolor,start,end,2)
    rotation = math.degrees(math.atan2(start[1]-end[1], end[0]-start[0]))+90
    pg.draw.polygon(screen, tricolor, ((end[0]+trirad*math.sin(math.radians(rotation)), end[1]+trirad*math.cos(math.radians(rotation))), (end[0]+trirad*math.sin(math.radians(rotation-120)), end[1]+trirad*math.cos(math.radians(rotation-120))), (end[0]+trirad*math.sin(math.radians(rotation+120)), end[1]+trirad*math.cos(math.radians(rotation+120)))))'
© www.soinside.com 2019 - 2024. All rights reserved.