Kusalin
Kusalin

Reputation: 11

C# DirectX Circle Drawing not working correctly

I've been trying to recode a C++ DirectX code to C# that would help me with Drawing a perfect circle. Currently I have this code that i translated by myself:

 private void Circle(int X, int Y, int radius, int numSides, Color color)
    {

        Vector2[] Line = new Vector2[128];
        float Step = (float)(Math.PI * 2.0 / numSides);
        int Count = 0;
        for (float a = 0; a < Math.PI * 2.0; a += Step)
        {

            float X1 = (float)(radius * Math.Cos(a) + X);
            float Y1 = (float)(radius * Math.Sin(a) + Y);
            float X2 = (float)(radius * Math.Cos(a + Step) + X);
            float Y2 = (float)(radius * Math.Sin(a + Step) + Y);
            Line[Count].X = X1;
            Line[Count].Y = Y1;
            Line[Count + 1].X = X2;
            Line[Count + 1].Y = Y2;
            Count += 2;
        }
        line.Begin();
        line.Draw(Line, color);
        line.End();               
    }

The problem is that the circle is drawn but also a Line from a point in the circle to the left top corner, like this.

enter image description here

Upvotes: 1

Views: 427

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32587

Don't iterate with a floating point variable. They might get imprecise during the iteration. In your case, the last step is probably very close behind the upper bound (instead of hitting it exactly). So it won't get calculated and left as the default (0, 0).

So use an integer iteration variable:

for (int i = 0; i < numSides; ++i)
{
    float a = i * Step;
    ...
}

Then, you can also get rid of Count.

Furthermore, you should make your coordinate buffer dynamic:

Vector2[] Line = new Vector2[2 * numSides];

Upvotes: 1

Related Questions