Search code examples
algorithmmathlinepseudocodeangle

How to get points X, Y coordinates from line angle?


So I have a 8x8 square. There is a line in it.

Line size == 8 angle == 0. 

One of line points is always on one of the top corners.

What would be a formula to retrieve points coordinates where line crosses borders of square? (positive angle means one of line points is 0, 0. negative 0, 8 )

What would be math formula for each of coordinates points? (in pseudo code if possible)


Solution

  • line_end_x = line_start_x + cos(angle)*line_length
    
    line_end_y = line_start_y + sin(angle)*line_length
    

    if your line crosses a vertical edge:

    intersection_x = edge_x
    intersection_y = line_start_y + (intersection_x - line_start_x) * tan(angle)
    

    if your line crosses a horizontal edge:

    intersection_y = edge_y
    intersection_x = line_start_x + (intersection_y - line_start_y) * tan(angle-pi/4)
    

    EDIT: corrected