Drawing arrows that follow the direction of a line in PyGame

In Pygame, how can I compute the coordinates for the three points of the arrow head, given the start point and end point of the arrow, so that the arrow points in the same direction as the line?

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)

      

I've tried playing with the corners and the gradient of the line, the fact that the Y coordinates are increasing downwards rather than upwards throws me off and I am very grateful for pushing in the right direction.

+3


source to share


2 answers


This should work:

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)))))

      



Sorry for the poorly organized code. But as you said, coordinates starting at the top left require a math change. Also, if you want to change the triangle from equal to different, you just need to change rotation +/- 120

in line 4 or 20*

for a different radius.

Hope it helps :)

+1


source


Let us denote the start and end coordinates as 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

      

+1


source







All Articles