Algorithm to detect when and where a point will exit a rectangle area

You need to find what edge is intersected first. Make equations for moving along both coordinates and calculate the first time of intersection.

Note that for geographic coordinates you might need more complex calculations because “rectangle” defined by Lat/Lon coordinates is really curvy trapezoid on the Earth surface. Look at “Intersection of two paths given start points and bearings” chapter on this page to get travel time.

vx = V * Cos(heading + Pi/2)   //for y-axis north=0
vy = V * Sin(heading + Pi/2)

x = x0 + vx * t
y = y0 + vy * t

//potential border positions    
if vx > 0 then
   ex = x2
else
   ex = x1

if vy > 0 then
   ey = y2
else
   ey = y1

 //check for horizontal/vertical directions
if vx = 0 then
return cx = x0,  cy = ey, ct = (ey - y0) / vy

if vy = 0 then
    return cx = ex, cy = y0, ct = (ex - x0) / vx


//in general case find times of intersections with horizontal and vertical edge line
  tx = (ex - x0) / vx
  ty = (ey - y0) / vy

 //and get intersection for smaller parameter value
 if tx <= ty then 
    return cx = ex, cy = y0 + tx * vy, ct = tx
 else
    return  cx = x0 + ty * vx,  cy = ey,  ct = ty

Leave a Comment