I know how to draw lines with DDA, but I want to learn a more efficient way and Google suggests Bresenham's line drawing algorithm is better than DDA.
Here is my implementation:
int x0 = Math.round(m_start.getPosition().getX());
int y0 = Math.round(m_start.getPosition().getY());
int x1 = Math.round(m_end.getPosition().getX());
int y1 = Math.round(m_end.getPosition().getY());
int dx = x1 - x0;
int dy = y1 - y0;
int parameter = 2 * dy - dx;
Point k = new Point(new Vector2D(x0, y0), m_display, PixelData.white());
k.DrawPoint();
for(int i = x0 + 1; i < x1; i++){
if(parameter < 0){
y0 += 1;
Point p = new Point(new Vector2D(i, y0), m_display, PixelData.white());
p.DrawPoint();
parameter += 2 * dy;
}
else{
y0 += 1;
Point p = new Point(new Vector2D(i, y0 + 1), m_display, PixelData.white());
p.DrawPoint();
parameter += 2 * dy - 2 * dx;
}
}
And here is the output:
As you can see, the line is not ending at the desired coordinate. That small dot is where it should end.
I checked the slope, dx and dy.
System.out.println(dx + " " + dy + " " + (dy/(float)dx));
Output:
100 50 0.5
The slope is below tan (pi/4).
How do I find the bug?