Главная страница | назад





Article #17917: Calculating an angle from two points

 Question and Answer Database

FAQ2917D.txt   Calculating an angle from two points
Category   :Object Pascal
Platform    :All
Product    :All 32 bit  

Question:
How can I tell the given angle expressed by two points?


Answer:
The following example shows how to tell the angle of a 
given point from the coordinate 0, 0. In this example, the 
caption of the form shows the current point and angle from 
the center of the form. The y coordinates are inverted to 
show a more natural north orientation where north is 
directly up.

Example:

const RADTODEG = 180 / Pi;

function AngleOfPt(pt : TPoint) : double;
begin
  Result := 0;
  if ((Pt.x = 0) and (Pt.y < 0)) then
    Result := 270 else
  if ((Pt.x = 0) and (Pt.y > 0)) then
    Result := 90 else
  if ((Pt.x > 0) and (Pt.y >= 0)) then
    Result := ArcTan(Pt.y / Pt.x) * RADTODEG else
  if ((Pt.x < 0) And (Pt.y > 0)) then
    Result := 180 - (ArcTan(Pt.y / Abs(Pt.x))* RADTODEG) else
  if ((Pt.x < 0) And (Pt.y <= 0)) then
    Result := 180 + (ArcTan(Pt.y / Pt.x) * RADTODEG) else
  if ((Pt.x > 0) and (Pt.y < 0)) then
    Result := 360 - (ArcTan(Abs(Pt.y) / Pt.x) * RADTODEG) else
  Result:=0;
end;

procedure TForm1.FormMouseMove(Sender: TObject; Shift:
TShiftState; X,  Y: Integer);
var
  XYMove : TPoint;
  RotateAngle : Double;
begin
  XYMove := (Point(x - (Form1.Width div 2),
                  (Form1.Height div 2) - y));
  RotateAngle :=
    AngleOfPt(XYMove);
  Form1.Caption := IntToStr(XYMove.x) + #32 +
                   IntToStr(XYMove.y) + ' = ' +
                   FloatToStr(RotateAngle);
end;

procedure TForm1.FormPaint(Sender: TObject);
begin
  Form1.Canvas.MoveTo(Form1.Width div 2,
                      0);
  Form1.Canvas.LineTo(Form1.Width div 2,
                      Form1.Height);
  Form1.Canvas.MoveTo(0,
                      Form1.Height div 2);
  Form1.Canvas.LineTo(Form1.Width,
                      Form1.Height div 2);
end;

procedure TForm1.FormResize(Sender: TObject);
begin
  Invalidate;
end;


7/16/98 4:31:28 PM
 

Last Modified: 01-SEP-99