Thursday, March 8, 2018

DELPHI - How get angle between points

This function:
{ ---------------------------------------------------------------------------
  Function calculate angle between points _iSource and _iDest in direction
  from _iSource.

  Returns value [0-360]. 
  -------------------------------------------------------------------------- }
function CalcAngle( _iSource, _iDest : TPoint ) : double;
var
  iAngle : extended;
begin
  iAngle := ArcTan2( _iSource.Y - _iDest.Y, _iSource.X - _iDest.X );

  result := ( iAngle * 180 ) / pi;

  { greater than 180 is negative -> change it }
  if result < 0 then
    result := 180 + ( 180 + result );
end;
And here is calling examle:
procedure TForm1.Button2Click(Sender: TObject);
var
  pt1, pt2, pt3, pt4 : TPoint;
  iResult1, iResult2, iResult3 : double;
begin
  pt1.x := 50; pt1.y := 50;
  pt2.x := 100; pt2.y := 100;
  pt3.x := 150; pt3.y := 50;
  pt4.x := 100; pt4.y := 150;

  iResult1 := CalcAngle( pt2, pt1 );
  iResult2 := CalcAngle( pt2, pt3 );
  iResult3 := CalcAngle( pt2, pt4 );

  ShowMessage( iResult1.ToString() + ' , ' + iResult2.ToString() + ' , ' + iResult3.ToString );
end;
Output:

No comments:

Post a Comment