I want to make a fancy animation where a point travels around a rectangle. I want to find the point's position at a time t
.
The rectangle is given by X
, Y
, Width
and Height
.
Is there an algorithm for this?
I've used sin
/cos
for circles. What's the equivalent approach for rectangles?
Answer
I'll assume your t goes from 0 to 1. (If not, just multiply to scale it appropriately.)
Figure out what proportion (0–1) each side is of the perimeter. (side length / total perimeter)
To find how much of every side is “filled in” at time t, iterate through sides, subtracting their proportions until t is depleted to a negative value. That last edge (which caused t to go negative) is filled by a proportion of (side length + remaining) / side length. The rest are not filled.
To get the exact vector position at t, multiply each side's vector by the proportion of that side that is filled, and add them.
This works for any polygon actually!
No comments:
Post a Comment