Skip to content Skip to sidebar Skip to footer

How To Calculate The Distance From A Given Point On The Surface Of A Square To Its Edge With Any Given Direction?

I am trying to figure out what the distance is from a point to the edge of a square's surface (regardless of its angle of direction). I've attached a rough drawing of what I'm talk

Solution 1:

As far as I understand, you define coordinates and direction and want to find intersection edge point. Make equations for moving along both coordinates and calculate the first time of intersection. There is no magic way without if's

vx = Cos(Direction)
vy = Sin(Direction)

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

if vy = 0 then
    return cx = ex, cy = y0


//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
 else
    return  cx = x0 + ty * vx,  cy = ey

Post a Comment for "How To Calculate The Distance From A Given Point On The Surface Of A Square To Its Edge With Any Given Direction?"