Carlos Femmer's Blog

Carlos Femmer lives in Lafayette, LA and builds a few solutions for JCLS and Agency Virtual Tours

Calculate Angle between 2 points using C#

February 20, 2006 11:19 by carlos

I was looking for a function in C# to calculate the angle between two points.  I could not find one online so I decided to post this one.  This is based on code from http://plan.cs.drexel.edu/projects/legorobots/software/angle.c .  I will post the code if anyone is interested.

private void btnCalcAngle_Click(object sender, EventArgs e)

{

double x1 = 0;

double y1 = 0;

double x2 = 5;

double y2 = 5;

MessageBox.Show("Angle between x and y: " + Angle(x1,y1,x2,y2).ToString());

}

public double Angle(double px1, double py1, double px2, double py2)

{

// Negate X and Y values

double pxRes = px2 - px1;

double pyRes = py2 - py1;

double angle = 0.0;

// Calculate the angle

if (pxRes == 0.0)

{

   if (pxRes == 0.0)

         angle = 0.0;

   else if (pyRes > 0.0)          angle = System.Math.PI / 2.0;

   else

         angle = System.Math.PI * 3.0 / 2.0;

}

else if (pyRes == 0.0)

{

   if (pxRes > 0.0)

         angle = 0.0;

   else

         angle = System.Math.PI;

}

else

{

   if (pxRes < 0.0)

         angle = System.Math.Atan(pyRes / pxRes) + System.Math.PI;

   else if (pyRes < 0.0)          angle = System.Math.Atan(pyRes / pxRes) + (2 * System.Math.PI);

   else

         angle = System.Math.Atan(pyRes / pxRes);

}

// Convert to degrees

angle = angle * 180 / System.Math.PI;return angle;

 

}


Tags:
Categories: C#
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

January 6. 2009 16:02