Elgun Majidov Elgun Majidov - 1 month ago 5
C# Question

How to keep the direction of line unchanged in the recursion?

With this function I want to draw a recursive tree but, when I call this function the direction of second line (which I want to draw recursively changes each time).

a
Is the angle between
x
and the first line,

b
Is the angle between first line and second line.

Photos:
This is the First level recursion
This is the second level of recursion the problem is at highlighted line
How can I fix this problem?

public void drawTree(int n, float l, float x, float y, float a, float b, float c,
float k1, float k2, float k3, float m2, float m3)
{
//float k = (float)Math.Pow(-1, n+1);
Pen p = new Pen(Color.Black);
Graphics gr = this.CreateGraphics();

float l1 = k1 * l;
float l2 = k2 * l;
float l3 = k3 * l;
float g = m3 * l;
float f = m2 * l;

gr.DrawLine(p, x, y, x + l * cos(a), y - l * sin(a));
if (n == 1) return;

drawTree(n - 1, l2, x + f * cos(a), y - f * sin(a), (a - b), b, c, k1, k2, k3, m2, m3);
}

Answer

Every time you compute the new point, you're subtracting it from y which if sin(a) was positive, would be fine, but since it's not, it flips from being a negative subtraction to a positive subtraction.

If you iterate one level deeper, the next line should be drawn correctly.

Try either using a positive value a or Math.Abs the resulting sin(a).

Comments