Skip to content

Instantly share code, notes, and snippets.

@DooblyNoobly
Last active October 11, 2019 01:24
Show Gist options
  • Save DooblyNoobly/514cc5e62446da9db4947160473ab15b to your computer and use it in GitHub Desktop.
Save DooblyNoobly/514cc5e62446da9db4947160473ab15b to your computer and use it in GitHub Desktop.
To convert a direction to an angle represented with a value range of -Pi and Pi where the 0 degree mark is Vector2.Up and then converting that value from degrees back to a heading direction.
public Vector2 direction;
[ContextMenu("Test dir to angle and back again")]
void DirToAngle()
{
var angleOfDir = Vector3.Angle(direction, transform.up);
var cw = Vector3.Cross(transform.up, direction).z < 0f;
if (!cw)
{
angleOfDir = -angleOfDir;
}
Debug.Log($"Angle is {angleOfDir}");
var backToDir = Quaternion.AngleAxis(-angleOfDir, Vector3.forward) * Vector3.up;
Debug.Log($"Converted back to dir: {(Vector2)backToDir}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment