I am writing a function that takes two coordinates, then calculates the points in between and draw the line.
The coordinates represent points in my array, the array is viewed by a print comand that prints it into a grid in console.
The function works,
output on
0,2 -> 3,9 in a 10 by 10 grid would look like
0000000000
0000000000
1000000000
1000000000
0100000000
0100000000
0100000000
0010000000
0010000000
0001000000
I'm wondering if i am doing this properly, or if there would be a better way to do it.
Links to similar functions or the code to them would help, trying to learn how best to do this
my code- i commented as best i could
Code:
void Line(int xs, int ys, int xe, int ye, int vl, int* array)
{
// first calculate slope using rise/run
float oy; // store last y coord
bool first = true; // to handle first time in loop
if (xe != xs) // can't have a slope of infinity
{
float s = ((float)ye - (float)ys) / ((float)xe - (float)xs); // slope
float b = ys - ((float) xs * s); // the B in the equation y = ax + b
for( float c = float(xs); c <= (float)xe; c++) // drawing loop
{
float y = (c * s) + b; // calculate the y
if ( (y + .5) >= ceil(y) ) // means it was x.5 or greater
{
y = ceil(y); // round up
}
else
{
y = floor(y); // its less then x.5 so round down
}
if (first) // first time in the loop
{
write(c, (int)y, vl, array);
oy = y;
first = false;
}
else // not first time in loop
{
for( int ty = oy ; ty < y; ty++) // draw from last coord, draw line towards next y, stop 1 before
{
write(c - 1, ty, vl, array);
}
oy = y;
}
}
// last point, should be xe, ye
write(xe, ye, vl, array);
}
}
Thanks for your time