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





Article #17928: Finding distance between two points.

 Question and Answer Database

FAQ2928D.txt   Finding distance between two points.
Category   :Object Pascal
Platform    :All
Product    :All 32 bit  

Question:
How can I find the distance between two points?


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

Example:

funcTion Distance(Pt1 : TPoint;
                  Pt2 : TPoint) : Double;
var
  dx : LongInt;
  dy : LongInt;
begin
  dx:= pt1.x - pt2.x;
  dy:= pt1.y - pt2.y;
  Result := Sqrt((Dx * Dx) + (Dy * Dy));
end;

procedure TForm1.FormMouseMove(Sender: TObject; Shift: 
TShiftState; X,  Y: Integer);
var
  Pt1 : TPoint;
  Pt2 : TPoint;
  Dist : Double;
begin
  Pt1.x :=  Form1.Width div 2;
  Pt1.y  :=  Form1.Height div 2;
  Pt2.x := x;
  Pt2.y := y;
  Dist := Distance(Pt1, Pt2);
  Form1.Caption := IntToStr(Pt2.x - Pt1.x) + #32 +
                   IntToStr(Pt1.y - Pt2.y) + ' = ' +
                   FloatToStr(Dist);
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