Drawing 2D polygons without using primitives

From XNAWiki
Jump to: navigation, search

First some code to draw a polygon using the line drawing code

//Draw n-gon
        public void DrawNgon(Vector2 Centre, float Radius, int N)
        {
            //szize of angle between each vertex
            float Increment = (float)Math.PI * 2 / N;
            Vector2[] Vertices = new Vector2[N];
            //compute the locations of all the vertices
            for (int i = 0; i < N; i++)
            {
                Vertices[i].X = (float)Math.Cos(Increment * i);
                Vertices[i].Y = (float)Math.Sin(Increment * i);
            }
            //Now draw all the lines
            for (int i = 0; i < N-1; i++)
            {
                DrawLine(Centre + Vertices[i]*Radius,Centre + Vertices[i + 1]*Radius);
            }
            DrawLine(Centre + Radius*Vertices[0],Centre + Radius*Vertices[N - 1]);
        }

Now a circle can just be an N-gon with many sides

//Draws a circle
        public void DrawCircle(Vector2 Centre, float Radius)
        {
            //compute how many vertices we want so it looks circular
            int N = (int)(Radius/2);
            DrawNgon(Centre, Radius, N);
        }