How do you generate a series of line segments given two points $(x_1,y_1), (x_2,y_2)$

computer sciencegeometrylinear algebra

I have a given line formed by $(x_1,y_1)$ and $(x_2,y_2)$, how would one go about generating some series of $N$ line segments?

I'm looking to break down a single line segment into "parts of $1$"? Not sure if that makes sense. I don't have a math background so apologies if that doesn't make sense and I'm happy to clarify.

Essentially if I have a line that looks like ____________ I'd like to break it down to – – – – – – – -.

I have been having trouble figuring out how to generate some $N$ line segments given a line segment formed by $(x_1,y_1)$ and $(x_2,y_2)$. I've thought of maybe using the midpoint formula and continually splitting it but I'm not sure what the base case to stop splitting would be other than if it's $\pm 1$ away from the starting point. Any help is appreciated for a better way or if my midpoint way is the wrong way!

edit: I'm attempting to use vector projection with line segments according to this answer here but having trouble understanding how to generate those line segments: https://gamedev.stackexchange.com/questions/90609/how-can-i-check-if-a-player-drawn-line-follows-a-path

edit2: I would like a formula (?) perhaps to generate some given (x,y) points given start and end points where each line segment has a length of 1. So for example, if I have a line that goes from the point (5,5) and to the point (5, 10) I want to generate a list of line segments that would look something like

[(5,5),(5,6)], [(5,6),(5,7)], [(5,7),(5,8)], [(5,8),(5,9)], [(5,9), (5,10)]. Now that I'm writing this perhaps I don't need the midpoint formula and I can simply add or subtract depending on the slope by one to each x,y coordinate until I reach the end point?

Best Answer

Your last attempt is almost correct. If you have a segment from $(x_1,y_1)$ to $(x_2,y_2)$ and you want to divide it into $n$ equal segments, first compute the displacement $(x_2-x_1, y_2-y_1)$ and then keep adding $\frac1n$ times this displacement to the last endpoint. The $k$th interval would be $$\left(x_1+\frac kn(x_2-x_1), y_1+\frac kn(y_2-y_1)\right)\tag1$$

You've probably noticed the problem with this formulation, namely that screen coordinates have to be whole numbers. I think the best approach would be to round each coordinate to the nearest integer. To round $x$ to the nearest integer use $$\lfloor x+.5\rfloor$$

Sorry I overlooked the requirement of a predetermined length. You can figure out then length of the displacement by the Pythagorean theorem -- it's just the distance between the two points. Then if the distance is $d$ and the desired length of a segment is $l$ let $\alpha = \frac ld$ and in place of $(1)$ use $$\left(x_1+k\alpha(x_2-x_1), y_1+k\alpha(y_2-y_1)\right)$$

Related Question