I want to rasterize a line using Bresenham's algorihm. My interpolated vertices shouldn't consist of diagonal steps. I did some search on StackOverflow and this topic seems to pretty much the thing I need.
The only problem I have with it is that I need to get the Same result if I changed the order of inputs, I mean if I swap the startPoint and endPoint of line I need to get the same set of interpolated vertices.
//the Method definition
List<Point> plotPoints(Point startPoint, Point endPoint);
//The thing I'm looking for
plotPoints(startPoint, endPoint)==plotPoints(endPoint, startPoint)
The code is almost same as The answer. However I did a bit customization for my purpose:
private float step=0.5;
public static List<Vector3> plotPoints(float x0, float y0, float x1, float y1) {
List<Vector3> plottedPoints = new List<Vector3>();
float dx = Mathf.Abs(x1 - x0), sx = x0 < x1 ? step : -step;
float dy = -Mathf.Abs(y1 - y0), sy = y0 < y1 ? step: -step;
float err = dx + dy, e2; /* error value e_xy */
for (; ; ) { /* loop */
if (x0 == x1 && y0 == y1) break;
plottedPoints.Add(new Vector3(x0,0, y0));
e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; } /* e_xy+e_x > 0 */
else if (e2 <= dx) { err += dx; y0 += sy; } /* e_xy+e_y < 0 */
}
return plottedPoints;
}