PointDistanceSquared returns the squared euclidean distance from the point p to the line segment l
(point Point)
| 340 | // PointDistanceSquared returns the squared euclidean distance from the point p |
| 341 | // to the line segment l |
| 342 | func (l *Line) PointDistanceSquared(point Point) float32 { |
| 343 | p1 := l.P1 |
| 344 | p2 := l.P2 |
| 345 | |
| 346 | x0 := point.X |
| 347 | y0 := point.Y |
| 348 | x1 := p1.X |
| 349 | y1 := p1.Y |
| 350 | x2 := p2.X |
| 351 | y2 := p2.Y |
| 352 | |
| 353 | l2 := (y2-y1)*(y2-y1) + (x2-x1)*(x2-x1) |
| 354 | if l2 == 0 { |
| 355 | return (y0-y1)*(y0-y1) + (x0-x1)*(x0-x1) |
| 356 | } |
| 357 | |
| 358 | t := ((x0-x1)*(x2-x1) + (y0-y1)*(y2-y1)) / l2 |
| 359 | |
| 360 | if t < 0 { |
| 361 | return (y0-y1)*(y0-y1) + (x0-x1)*(x0-x1) |
| 362 | } else if t > 1 { |
| 363 | return (y0-y2)*(y0-y2) + (x0-x2)*(x0-x2) |
| 364 | } |
| 365 | |
| 366 | return (x0-(x1+t*(x2-x1)))*(x0-(x1+t*(x2-x1))) + |
| 367 | (y0-(y1+t*(y2-y1)))*(y0-(y1+t*(y2-y1))) |
| 368 | } |
| 369 | |
| 370 | // Normal returns the left hand normal of the line segment l |
| 371 | func (l *Line) Normal() Point { |