I have the following hexagonal grid and trying to calculate the degrees to each edge hexagon from the center (light blue):
The blue highlighted hex is correct at 0 degrees and that quadrant (lower right) is correct. Here is my angle calculation method:
private static function calculateAngle(hex1:Hexagon, hex2:Hexagon):Number {
// hex1 is always passed in as the grid center or start
var diffY:Number = Math.abs(hex2.center.y) - Math.abs(hex1.center.y);
var diffX:Number = Math.abs(hex2.center.x) - Math.abs(hex1.center.x);
var radians:Number = Math.atan(diffY / diffX);
return radians * 180 / Math.PI;
}
Why are the remaining angles (text in each hexagon) incorrect?
You're really close to correct; you just need to compensate for the periodicity of atan
. The standard way to do this is to use atan2
, which returns a signed angle in (-pi, pi]
instead of an unsigned angle in [0, pi)
. You can do so like this:
var radians:Number = Math.atan2(
hex2.center.y - hex1.center.y, hex2.center.x - hex1.center.x);
Note that I didn't include the call to abs
in there: the signedness of those values is needed for atan2
to know which quadrant its in!
Edit: if you're looking for an angle in [0, pi]
, which represents the minimum angle between the center hex and the blue-highlighted hex, you can just take the absolute value of the result of atan2
: return Math.abs(radians) * 180 / Math.PI
; the question leaves it a little unclear as to which one you're asking for.