Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a line formed by two points greater than 45 degrees off of the horizontal

Tags:

c#

math

I am trying to find out if a line defined by two points is greater than or equal to 90 degrees compared to the horizontal. Here is the code I used

bool moreThan90 = false;
double angle = Math.Atan((double)(EndingLocation.Y - Location.Y) / (double)(EndingLocation.X - Location.X));
if (angle >= Math.PI / 2.0 || angle <= -Math.PI / 2.0)
    moreThan90 = true;

Did I do this correctly or is there a better built in function in .Net that will find this?

EDIT -- Actually I messed up my question I ment to say 45 off of horizontal not 90. however the answers got me to a point where I can figure it out (really I just needed to be pointed at Atan2).

like image 977
Scott Chamberlain Avatar asked Jan 23 '26 04:01

Scott Chamberlain


2 Answers

A line that is more than 90 degrees from the horizontal will have its EndLocation.x at a smaller x value than Location.x.

So you don't need all the atan nonsense, this should be enough:

if (EndingLocation.X < Location.X)
    moreThan90 = true;

EDIT:

Seems the OP meant 45 degrees not 90, which means that the above simplification no longer holds. For this it might be better to use atan2 (as Slaks pointed out) But in the spirit of not using tan:

if (Math.Abs(EndingLocation.X - Location.X) > Math.Abs(EndingLocation.Y - Location.Y) && 
    EndingLocation.X < Location.X)
    moreThan45 = true;

Note that you only need the 2nd check if you only want lines which point to the right

like image 174
pheelicks Avatar answered Jan 25 '26 20:01

pheelicks


You should call Math.Atan2, like this:

double angle = Math.Atan2(EndingLocation.Y - Location.Y, 
                          EndingLocation.X - Location.X);

if (Math.Abs(angle) >= Math.PI / 2.0)
    moreThan90 = true;
like image 39
SLaks Avatar answered Jan 25 '26 21:01

SLaks