1
$\begingroup$

I stumbled upon the need to get a random point on the perimeter of a rectangle while making a game, the solution programmatically is easy enough, tho i was curious of a mathematical solution too.

Say we have a random Distance we want to travel from the TopLeft corner of the rectangle along all its sides. We known the Width and Height of the rectangle, including the Distance or Length that we'll travel around it.

Our point will only ever be on the edge of the rectangle and never inside it.

Is there a simple equation to get the X,Y coordinates?

Here's an illustration in mspaint

Note that our random Distance can be the full perimeter of the rectangle, having us travel all around it completely.

$\endgroup$
0
$\begingroup$

Assuming positive $x$ is right and positive $y$ is down, and the rectangle has width $w$ and height $h$, and the distance travelled is $0\le d\le 2(w+h)$ then

$$(x,y) = \begin{cases}(d,0) &\text{for } 0\le d\le w\\ (w,d-w) &\text{for } w\le d\le w+h\\ (2w+h-d,h) &\text{for } w+h\le d\le 2w + h\\ (0,d-2w-h) &\text{for } 2w+h\le d\le 2(w+h)\\\end{cases}$$

If $d$ exceeds $2(w+h)$ replace $d$ by its remainder when divided by $2(w+h)$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.