I've been banging my head over this. I'm terrible with rotations, especially when it comes to translating them from and to 2D space.
So what I have is a 96px square sprite that has it's pivot set to 0.5 and 0 (bottom center) at the center of the screen and the default arrow direction is 0 degrees (pointing up). When the player takes damage, I'm trying to make this arrow rotate around the pivot (center of the screen) and show which direction the damage came from. So if the damage came from behind them, the arrow would be at 180 degrees (pointing down), in front 0 degrees (pointing up), to the left 270 degrees (pointing left)... Well, you get the idea.
Here is what I got, but it just doesn't seem to work right:
Vector3 targetPos = target.transform.position;
Vector3 screenpos = Camera.main.WorldToScreenPoint(targetPos);
if(screenpos.z < 0)
screenpos *= -1;
float angle = Mathf.Atan2(screenpos.y, screenpos.x);
angle -= 90 * Mathf.Deg2Rad;
ArrowSprite.transform.localRotation = Quaternion.Euler(0, 0, angle * Mathf.Rad2Deg);
I found some code somewhere and this is the result I came up with while tweaking it trying to make it work as I don't quite understand what the -= 90 is for. I do understand taking Atan2 and turning it into a direction and then back to radians for the Quaterniun.Euler, but I'm clearly not understanding the full logic of this code or I'd be able to get my arrow to point in the correct direction in relation to the incoming damage.
↧