2017-04-20 129 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