The problem:

We have a squared box of size w*w.

Inside the box, we have a point at (x,y).

From the point we draw a line at some angle d.

If x, y, d, and w are known, find the distance to the closest wall of the box.

x and y are always positive and less then w (point is always inside the box). The d can be anything.

On the attached image I put two points. I need to know the length of green lines.

From a simple definitions of sin and cos, I have four distances to the four walls of the box

dl = (0 - x) / cos d

db = (0 - y) / sin d

dr = (w - x) / cos d

dt = (w - y) / sin d

From the set {dl, db, dr, dt} remove negative values (those are distances along the same line but in opposite directions).

And the final answer is the minimal from two remaining values.

Looks like the final answer is correct, but solutiona is fairly complicated. Maybe I am not seeing the obvious, but is it possible to reduce this algorithm to a one formula?