Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compass direction <=> degree measure abstract for Haxe. Useful for me, maybe for you.
package entities;
import nape.geom.Vec2;
/**
* @author MSGHero
*/
@:enum
abstract Direction(Int) {
var E = 0;
var NE = 45;
var N = 90;
var NW = 135;
var W = 180;
var SW = 225;
var S = 270;
var SE = 315;
var NONE = -1;
@:from
public static function fromInt(i:Int):Direction {
// not using mod: [-360, 720) range
if (i < 0) i += 360;
if (i >= 360) i -= 360;
return switch (i) {
case 0: E;
case 45: NE;
case 90: N;
case 135: NW;
case 180: W;
case 225: SW;
case 270: S;
case 315: SE;
case _: NONE;
}
}
@:to
public inline function toInt():Int {
if (this < 0) this += 360;
if (this >= 360) this -= 360;
return this;
}
@:to
public function toVec2():Vec2 {
return Vec2.get(
// x
switch (this) {
case Direction.E: 1;
case Direction.W: -1;
case Direction.NE, Direction.SE: .707;
case Direction.NW, Direction.SW: -.707;
case _: 0;
},
// y
switch (this) {
case Direction.S: 1;
case Direction.N: -1;
case Direction.NW, Direction.NE: -.707;
case Direction.SW, Direction.SE: .707;
case _: 0;
}
};
}
@:op(A + B) public function add(rhs:Direction):Direction {
return fromInt(this + rhs.toInt());
}
@:op(A - B) public function sub(rhs:Direction):Direction {
return fromInt(this - rhs.toInt());
}
@:op(++A) public inline function incPre():Direction {
this += 45;
return fromInt(this);
}
@:op(A++) public inline function incPost():Direction {
var d = fromInt(this);
this += 45;
return d;
}
@:op(--A) public inline function decPre():Direction {
this -= 45;
return fromInt(this);
}
@:op(A--) public inline function decPost():Direction {
var d = fromInt(this);
this -= 45;
return d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment