Snapping direction to forward/backward/left/right

Alright I’m working with a game on a grid with a click to move feature to navigate from tile to tile. The last part of the movement I need is when the player arrives at the tile it needs to change its rotation to be looking either 0 degrees, 90 degrees, 180 degrees, or -90 degrees relative to the view. Basically if the player isn’t moving it is snapped to one of the 4 directions. I’m not sure how to find which is the closest rotation direction to snap to, any thoughts?

I’ve considered just getting the player’s current rotation and comparing it to the closest 2 rotations, but I’m not exactly sure how to make that work in code.

You probably want to compare transform.forward to the cardinal directions using Vector3.Angle. Comparing two quaternions is confusing, but comparing two direction vectors is easy.

Hm ok I’ll give that a whirl. I’ve never used Vector3.angle before so this might get interesting. Thanks for the help

It’s pretty straightforward.

float angleBetween = Vector3.Angle(transform.forward, Vector3.forward);
1 Like