I'm coding a game in pygame and I need a function that accepts a start (x1,y1) and an end (x2,y2) as arguments. Using the pygame line drawing function, I can just draw a line straight from one point to the next like this
def make_bullet_trail(x1,y1,x2,y2):
pygame.draw.line(screen,(0,0,0),(x1,y1),(x2,y2))
however, I want the line to be no more than 10 pixels long starting from the x1,y1, so if the points are 100 pixels away, 90 pixels of the line are not drawn. How can I write this dynamically so that no matter where these 4 points are the line always starts drawing from one to the other and stops after ten pixels?
Before you call the line drawing function, you can adjust your (x2, y2) point. You probably want to do something like this:
# Get the total length of the line
start_len = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# The desired length of the line is a maximum of 10
final_len = min(start_len, 10)
# figure out how much of the line you want to draw as a fraction
ratio = 1.0 * final_len / start_len
# Adjust your second point
x2 = x1 + (x2 - x1) * ratio
y2 = y1 + (y2 - y1) * ratio
Since you're using pygame, though, you might want an integer number of pixels. In that case, you probably want to take int(round())
for the output x2 and y2, and you also want to adjust the ratio so that you get exactly 10 pixels in the major (longest) direction. To do this adjustment, you can simply use max(abs(x2-x1), abs(y2-y1))
for the length. It's not the real length, but it will insure you get the same number of pixels drawn each time.