Skip to main content

Any-sided shapes with angles

One formula draws a triangle, pentagon or hexagon — just change the number of sides.

A circle used distance; a box used edges. A regular polygon — triangle, pentagon, hexagon — uses the ANGLE around the center. If you know the direction from the middle to a pixel, you know which of the polygon’s flat sides that pixel faces, and how far it is from that side. atan(pos.x, pos.y) gives you that angle, and one compact formula turns it into a distance to the nearest edge.

The magic line is d = cos(floor(0.5 + a/r) * r - a) * length(pos), where r is one slice of the circle (2π / number of sides). You do not need to memorize it — the thing to see is that a single sides number controls the whole shape. Change it and the triangle becomes a pentagon becomes a hexagon.

Change sides to 3 and you get a triangle; 5 a pentagon; 8 an octagon; push it high and it rounds back into a circle. This is how shaders draw gems, stars, badges and UI icons — the same formula, one parameter.

Tip Because the shape is a smooth field of similar-sized blobs, a pixel-match grader cannot reliably tell a hexagon from a pentagon, so this one is a playground rather than a graded exercise. Sweep sides from 3 upward and watch the shape grow more rounded.
Quick check

In the polygon formula, what does changing the sides number do?

▶ Draw polygons Change sides for different shapes, or add u_time to the angle a to spin the polygon.
Wayline
Tools, assets and tutorials for game makers
Get started