Badwrong

GameMaker - Line-circle Intersect

Mar 11th, 2021 (edited)
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function LineCircleIntersect(_cx, _cy, _r, _x1, _y1, _x2, _y2)
  2. {
  3.     // Find intersect points with a line and a circle
  4.     // Circle origin [_cx, _cy] with radius _r
  5.     // Line of [_x1, _y1] to [_x2, _y2]
  6.    
  7.     #macro M_EPS (math_get_epsilon())
  8.    
  9.     _cx = _x1 - _cx;
  10.     _cy = _y1 - _cy;
  11.    
  12.     var _vx  = _x2 - _x1,
  13.         _vy  = _y2 - _y1,
  14.         _a   = _vx * _vx + _vy * _vy,
  15.         _b   = 2 * (_vx * _cx + _vy * _cy),
  16.         _c   = _cx * _cx + _cy * _cy - _r * _r,
  17.         _det = _b * _b - 4 * _a * _c;
  18.    
  19.     if (_a <= M_EPS || _det < 0)
  20.     {
  21.         // No real solutions.
  22.         return noone;
  23.     }
  24.     else if (_det == 0)
  25.     {
  26.         // Line is tangent to the circle
  27.         var _t = -_b / (2 * _a);
  28.         var _p1 = { X : _x1 + _t * _vx, Y : _y1 + _t * _vy };
  29.         return [_p1, _p1];
  30.     }
  31.     else
  32.     {
  33.         // Line intersects circle
  34.         _det = sqrt(_det);
  35.         var _t1 = (-_b - _det) / (2 * _a);
  36.         var _t2 = (-_b + _det) / (2 * _a);
  37.        
  38.         // First point is closest to [_x1, _y1]
  39.         return [{ X : _x1 + _t1 * _vx, Y : _y1 + _t1 * _vy },
  40.                 { X : _x1 + _t2 * _vx, Y : _y1 + _t2 * _vy }];
  41.     }
  42. }
Add Comment
Please, Sign In to add comment