Converting 2D square movement direction to procedural animation

Hello, and thanks for checking out my question!

I am trying to figure out a good way to animate a 2D square’s rotation based on which direction the player is moving, so that the face of the square closest to this direction is rotated towards the point.

The square is the player, has 2D physics with a collider, and although I would like it to be accurate down to 1 degree I am fine with covering the major and minor cardinal directions.

One thought I had was to create a circle sliced into 8 pieces and raycasting it to figure out which slice the vector falls within, but I don’t even know if I can achieve this in a performant way. Example:

57502-example-raycast-square-coords.jpg

I searched the Asset Store for a 2d character controller but was unable to find one that advertised this behavior. The original approach was to convert the direction to a degree around the center of the square in comparison to the zero-degree side of the square, and then try to figure out which side to rotate towards the point, but my attempts using Vector2.Angle() have been unsuccessful.

Thanks again for your time! This is my first question here, so please let me know if I need to provide more information.

Well, if you get an angle to somewhere, like the mouse cursor, you can quantize the angle to 8 sectors.

public static float QuantizedRadian(float radian, int sectors = 8)
{
    float unit = radian / (Mathf.PI * 2);
    int sector = Mathf.FloorToInt(unit * sectors);
    return sector * Mathf.PI * 2 / sectors;
}

That will give you a radian that snaps to 8 different angles etc. But your example also was offset by half a sector in radians so you need to take that into account. Anyway, if you want a more complete example, I wrote a demo. The demo takes angle to mouse, offsets & quantizes the angle. Additionally, it shows which sector the angle points to.