Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make trigonometry code more efficient

I need help to make my code below more efficient, and to clean it up a little.

As shown in this image, x and y can be any point around the whole screen, and I am trying to find the angle t. Is there a way I can reduce the number of lines here?

Note: The origin is in the top left corner, and moving right/down is moving in the positive direction

o := MiddleOfScreenX - x;
a := MiddleOfScreenY - y;

t := Abs(Degrees(ArcTan(o / a)));

if(x > MiddleOfScreenX)then
  begin
    if(y > MiddleOfScreenY)then
      t := 180 + t
    else
      t := 360 - t;
  end
else
  if(y > MiddleOfScreenY)then
    t := 180 - t;

The code is in pascal, but answers in other languages with similar syntax or c++ or java are fine as well.

:= sets the variable to that value
Abs() result is the absolute of that value (removes negatives)
Degrees() converts from radians to degrees
ArcTan() returns the inverse tan
like image 737
putonajonny Avatar asked Dec 26 '22 22:12

putonajonny


1 Answers

see this http://www.cplusplus.com/reference/clibrary/cmath/atan2/ for a C function.

atan2 takes 2 separate arguments, so can determine the quadrant.

pascal may have arctan2 see http://www.freepascal.org/docs-html/rtl/math/arctan2.html or http://www.gnu-pascal.de/gpc/Run-Time-System.html

o := MiddleOfScreenX - x;
a := MiddleOfScreenY - y;

t := Degrees(ArcTan2(o, a));
like image 104
ctrl-alt-delor Avatar answered Jan 04 '23 23:01

ctrl-alt-delor