December 03, 2020, 07:29:00 PM

### Author Topic: [bmx] Distance to line by Otus [ 1+ years ago ]  (Read 682 times)

#### BlitzBot

• Jr. Member
• Posts: 1
##### [bmx] Distance to line by Otus [ 1+ years ago ]
« on: June 29, 2017, 12:28:38 AM »
Title : Distance to line
Author : Otus
Posted : 1+ years ago

Description : I think this code is quite optimized.

The c code is a bit faster.

Code :
Code: BlitzMax
1. Function DistanceToLineSegment:Double(ax:Double,ay:Double,..
2.                 bx:Double,by:Double, px:Double,py:Double)
3.         'Returns the distance from p to
4.         '       the closest point on line segment a-b.
5.
6.         Local dx:Double=bx-ax
7.         Local dy:Double=by-ay
8.
9.         Local t:Double =  ( (py-ay)*dy + (px-ax)*dx ) / (dy*dy + dx*dx)
10.
11.         If t<0
12.                 dx=ax
13.                 dy=ay
14.         ElseIf t>1
15.                 dx=bx
16.                 dy=by
17.         Else
18.                 dx = ax+t*dx
19.                 dy = ay+t*dy
20.         End If
21.
22.         dx:-px
23.         dy:-py
24.
25.         Return Sqr(dx*dx + dy*dy)
26.
27. End Function
28.
29. Function DistanceToLine:Double(ax:Double,ay:Double, bx:Double,by:Double, px:Double,py:Double)
30.         'Returns the distance from p to the closest point
31.         '       ont the line passing through a and b.
32.
33.         Local dx:Double=bx-ax
34.         Local dy:Double=by-ay
35.
36.         Return ( (ay-py)*dx + (px-ax)*dy ) / Sqr(dy*dy + dx*dx)
37.
38. End Function
39.
40. 'in.c:
41.
42. double dx;
43. double dy;
44. double t;
45.
46. double DistanceToLineSegment(double ax, double ay, double bx, double by, double px, double py)
47. {
48.         dx = bx-ax;
49.         dy = by-ay;
50.
51.         t = ( (py-ay)*dy + (px-ax)*dx ) / (dy*dy + dx*dx);
52.
53.         if (t<0) {
54.                 ax-=px;
55.                 ay-=py;
56.                 return sqrt(ax*ax + ay*ay);
57.         }
58.         if (t>1) {
59.                 bx-=px;
60.                 by-=py;
61.                 return sqrt(bx*bx + by*by);
62.         }
63.
64.         ax+=t*dx-px;
65.         ay+=t*dy-py;
66.         return sqrt(ax*ax + ay*ay);
67. }
68.
69. double DistanceToLine(double ax, double ay, double bx, double by, double px, double py)
70. {
71.         dx = bx-ax;
72.         dy = by-ay;
73.
74.         return ( (ay-py)*dx + (px-ax)*dy ) / sqrt(dy*dy + dx*dx);
75. }