2017-04-20 132 views
3

在Pygame中,如何计算箭头头部三点的坐标,给定箭头的起点和终点,以便箭头指向与该行相同的方向?绘制符合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坐标增加向下而不是向上抛出我了,我真的很感激,在正确的方向轻推。

+0

的[查找坐标在一行的末尾画箭头(isoscele三角形)可能的复制(http://stackoverflow.com/questions/31462791/find-coordinates-to-draw-arrow-head-isoscele-triangle-at-the-end-of-a-line) – Spektre

+0

appart你可能想要的重复QA也可以看到这一点:[将旋转应用到基于结束正常管的圆柱体](http://stackoverflow.com/a/39674497/2521214) – Spektre

回答

1

这应该工作:

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 +/- 12020*更改为不同的半径即可。

希望这有助于:)

1

我代表开始和结束的坐标为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