Calculate the Distance to the Edge of Any Shape*
Some draggable nodes with different shapes and sizes. In order to calculate the positions of the arrows, you need to know the distance from the center of the shape to the edge at any given angle.
Just finished the initial build of another project using the Constellation Framework™. (-;
One of the new features that I implemented for this client was the ability to configure nodes with different shapes. Previously, I'd only used circles because it's really easy to calculate the distance to the edge of a circle—it's always the same, you usually set it yourself, and it's called "the radius."
Throw in some triangles, squares, and pentagons and things aren't so simple anymore. I ended up writing a class that represents equilateral shapes, that is, shapes whose sides are all the same length. One of the methods will take any angle and tell you how far pixel Joe would have to walk to get from the center of the shape to the edge of the shape at that angle. Here's the important bit of code:
public function getCenterToEdgeDistance(angle:Number):Number { // is it a circle? if (_numSides == 1) return _radius; // this shape might be rotated var a:Number = (angle - _rotation); // make sure the angle is between 0 and 360°/numSides while (a < 0) a += Math.PI * 2; a = a % (Math.PI * 2 / _numSides); // some angle tweaking if (a >= 0 && a <= Math.PI * 1 / _numSides) a = Math.PI * 1 / _numSides - a; if (a > Math.PI * 1 / _numSides && a <= Math.PI * 2 / _numSides) a = a - Math.PI * 1 / _numSides; // ...and the final calculation return _radius * Math.cos(Math.PI / _numSides) / Math.cos(a); }
Two pages of 8.5 x 11" suffered my mathematical scribblings before I got the that figured out. That little problem was a snarky little bugger but all in all it was fun and it just makes the interface look that much more professional.
If you find this useful, give me a shout. I'd be curious to know what you used it for.
* Okay, so it won't calculate the distance to the edge of any shape but it will work on any equilateral shape.


