[英]Drawing arrowheads which follow the direction of the line in 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坐標向下而不是向上增加的事實讓我失望,我真的很感激在正確的方向上輕推。
這應該工作:
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*
。
希望這可以幫助 :)
我將起始和結束坐標表示為startX, startY, endX, endY
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
弗拉基米爾的答案很棒! 對於將來訪問的任何人來說,這里的功能是控制箭頭的每個方面:
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)))))'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.