23 April, 2013

The Algorithm for triangles and hexagons

So I thought that it might be a good time to share the algorithm I devised in order to create triangles and hexagons in a standard 3-space.  I'll share just the one for a triangle since the hexagon is just 6 triangles put together.

In order to do it you will need some variables that are important. This will be written in pseudo code and should be easily adapted to whatever language you wish to translate it to.

In order to do it you will need some variables that are important.

// This variable is the height of an equilateral triangle
float depth = Math.sqrt(3)/2;

//Then we need some counters for the loops
float count = 0;
float countstart = 0;
float countstop = 50; // This can be for however large you wish to draw

// This first one is built in 2 space
for( int y = 0, y < 50, y++) //Note that the target number of loops is the same size as countstop
{
    count = countstart;
    while( count < countstop) // This is where the X element is drawn
    {
        Draw an equilateral triangle the uses the following vertices;
        Vertex1 ( x = count, y= y * depth);
        Vertex2 (x = count + 1, y= y * depth );
        Vertex3 (x =count + 0.5, y = (y + 1) * depth );
        count = count + 1;
    }
    countstart = countstart + 0.5;
    countstop = countstop - 0.5;
}

The one for creating triblocks in 3 dimensions is fairly similar

//These variable are used once again
float count = 0;
float countstart = 0;
float countstop = 50; // This can be for however large you wish to draw

//There are only slight variations to build blocks in 3-space
// This second one is built in 3 space
for (int z = 0, z < 50 , z++)
{
    for( int y = 0, y < 20, y++) //Note that the target number of loops is the same size as countstop
    {
        count = countstart;
        while( count < countstop) // This is where the X element is drawn
        {
           if( z=0)
           {
               Only draw a zpos triblock
           }
           else
           {
               Draw a zpos triblock
               Draw a zneg triblock
           }
           count = count + 1;
        }
    }
    countstart = countstart + 0.5;
    countstop = countstop - 0.5;
}

Please note that the y loop can have as many iteration as you wish since the triangle is in the z  and x portions.  Again to create a hexagon one would need 6 of these triangle formations.

No comments:

Post a Comment