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:
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.
This question is pretty similar to this other question that I provided an answer for. Although, it uses 4 sectors ins$$anonymous$$d of 8. It should be pretty simple to modify the Quantize method to support 8 sectors. I am sure it's possible to quantize the angle without having to do the ugly if tests too, but uh, I left that as an exercise :)
You can also play a webgl demo here to get an idea if it's somewhat you're looking for.
Wow, ok that may be what I was looking for. I've downloaded the package and am digging through it now. Thanks for your help!
Answer by Statement · Nov 03, 2015 at 07:24 PM
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.
Binaries: WebGL Demo, Unity Package
Code: Quantize.cs, QuantizedExample.cs
Project: Github