Skip to content

Instantly share code, notes, and snippets.

@StagPoint
Last active October 4, 2025 22:24
Show Gist options
  • Save StagPoint/bedb9ffa11b1a22f4ea5f248ffed63e1 to your computer and use it in GitHub Desktop.
Save StagPoint/bedb9ffa11b1a22f4ea5f248ffed63e1 to your computer and use it in GitHub Desktop.
Methods for converting between direction vectors and cardinal direction values in Godot C#
using Godot;
#pragma warning disable CA1050
/// <summary>
/// Cardinal directions, ordered clockwise from East
/// </summary>
public enum CardinalDirection
{
Unknown = -1,
E, // East
SE, // Southeast
S, // South
SW, // Southwest
W, // West
NW, // Northwest
N, // North
NE, // Northeast
}
/// <summary>
/// Extension methods for converting between <see cref="Vector2"/> direction vectors and <see cref="CardinalDirection"/> values
/// </summary>
public static class Vector2DirectionExtensions
{
/// <summary>
/// Direction vectors corresponding to the <see cref="CardinalDirection"/> enum values
/// </summary>
private static Vector2[] _directionVectors =
[
Vector2.Right,
new Vector2( 0.70710677f, 0.70710677f ),
Vector2.Down,
new Vector2( -0.70710677f, 0.70710677f ),
Vector2.Left,
new Vector2( -0.70710677f, -0.70710677f ),
Vector2.Up,
new Vector2( 0.70710677f, -0.70710677f )
];
/// <summary>
/// Converts a <see cref="CardinalDirection"/> value to the corresponding normalized direction vector
/// </summary>
/// <param name="direction">The <see cref="CardinalDirection"/> value to convert</param>
/// <returns>Returns the corresponding direction vector</returns>
public static Vector2 ToDirectionVector( this CardinalDirection direction )
{
return _directionVectors[ (int)direction ];
}
/// <summary>
/// Converts a normalized direction vector to the closest <see cref="CardinalDirection"/> value
/// </summary>
/// <param name="directionVector">A normalized 2D direction vector</param>
/// <returns>Returns the nearest <see cref="CardinalDirection"/> value that represents the direction vector</returns>
public static CardinalDirection ToCardinalDirection( this Vector2 directionVector )
{
var angle = Mathf.Atan2( directionVector.Y, directionVector.X );
var octant = (int)Mathf.Round( 8 * angle / Mathf.Tau + 8 ) % 8;
return (CardinalDirection)octant;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment