Deputy McMunch
Deputy McMunch

Reputation: 37

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 talking about. enter image description here

The grid is centered around the square (although poorly drawn). The distance from the center of the square to the center of the circle. I was hoping to find a way to calculate the distance to the edge of the square from the circle no matter which direction it is headed without having to use a lot of if-else statements in my code.

Let me know if you have any nice ideas!

Upvotes: 0

Views: 1112

Answers (1)

MBo
MBo

Reputation: 80277

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

Upvotes: 1

Related Questions