I have (with assistance) created a function that plots and draws a line of blocks within a 3D space. Generally this is performed in a 64x64x64 gridded cube.
This is the code I have:
internal static int DrawLine(Player theplayer, Byte drawBlock,
int x0, int y0, int z0, int x1, int y1, int z1)
{
int blocks = 0;
bool cannotUndo = false;
bool detected = false;
int dx = x1 - x0;
int dy = y1 - y0;
int dz = z1 - z0;
DrawOneBlock(theplayer, drawBlock, x0, y0, z0, ref blocks, ref cannotUndo);
if (Math.Abs(dx) > Math.Abs(dy) &&
Math.Abs(dx) > Math.Abs(dz) &&
detected == false)
{
detected = true;
float my = (float)dy / (float)dx;
float mz = (float)dz / (float)dx;
float by = y0 - my * x0;
float bz = z0 - mz * x0;
dx = (dx < 0) ? -1 : 1;
while (x0 != x1)
{
x0 += dx;
DrawOneBlock(theplayer, drawBlock,
Convert.ToInt32(x0),
Convert.ToInt32(Math.Round(my * x0 + by)),
Convert.ToInt32(Math.Round(mz * x0 + bz)),
ref blocks, ref cannotUndo);
}
}
if (Math.Abs(dy) > Math.Abs(dz) &&
Math.Abs(dy) > Math.Abs(dx) &&
detected == false)
{
detected = true;
float mz = (float)dz / (float)dy;
float mx = (float)dx / (float)dy;
float bz = z0 - mz * y0;
float bx = x0 - mx * y0;
dy = (dy < 0) ? -1 : 1;
while (y0 != y1)
{
y0 += dy;
DrawOneBlock(theplayer, drawBlock,
Convert.ToInt32(Math.Round(mx * y0 + bx)),
Convert.ToInt32(y0),
Convert.ToInt32(Math.Round(mz * y0 + bz)),
ref blocks, ref cannotUndo);
}
}
if (detected == false)
{
detected = true;
float mx = (float)dx / (float)dz;
float my = (float)dy / (float)dz;
float bx = x0 - mx * z0;
float by = y0 - my * z0;
dz = (dz < 0) ? -1 : 1;
while (z0 != z1)
{
z0 += dz;
DrawOneBlock(theplayer, drawBlock,
Convert.ToInt32(Math.Round(mx * z0 + bx)),
Convert.ToInt32(Math.Round(my * z0 + by)),
Convert.ToInt32(z0),
ref blocks, ref cannotUndo);
}
}
return blocks;
}
It should queue up the block drawing and return the number of blocks it has drawn. The problem is that it is not drawing an un-broken line. In certain instances it leaves gaps between the blocks when at the very least all blocks should be connected by their vertices.
The only part of the code I struggled with is that I was calculating the largest difference in axis and creating a slope constant. I ran into an issue when trying to do a perfect diagonal line. All values were equal so I just defaulted to the z axis – this is where I believe the issue exists.
Maybe the Bresenham line algorithm modified to (hopefully) work in 3D could be an alternative for you?