I'm trying to find the orientation for an entity, as an angle in [0º-360º). I've searched for an answer and tried to implement something of my own, but it always fails on the edge cases. For a better understanding of what I am trying to achieve I've created the following image.
EDIT: It is worth mentioning that I do the conversions to and from radians where needed. Additionally, this is used for an internal simulation (meaning this will not be rendered on screen).
What is known: the center point coordinates which is always at (0,0) and the position of the red entity (x,y)
What needs to be computed: the orientation of the red entity such as it faces the center point (0, 0) in degrees 0-359
In my particular case I have to support negative coordinates. The degrees start at 0 which is at the top and goes CW.
What I tried
I've tried using atan2(y, x) which I almost got working, but it fails at some edge cases as I will describe.
When the entity is in the first quadrant I get, let's say 45 degrees, but this is not good in my case, because if the entity is in the first quadrant and it's facing the center the angle should be between 270 and 180. So I did some mapping and it seems to be working.
When the entity is in the second quadrant I get, let's say -45 degrees, which again is not good because I need it to be in range of 0-359. So I check if the degree is less than 0, add 360 and mod by 360. The result I get is good since it's between 270 and 359.
I could go on about the rest of the quadrants, but then I get another issue: when the x or y coordinates for the entity are 0 (only one, not both).
I could write some if cases to adapt the result accordingly, but I figured there must be a smarter solution to this and a faster one, since this needs to be computed 60 times a second.
I've also tried some custom math, using triangles, but ultimately I have to manually do some checks to get the correct answer.
I don't know if this is of any value for the answer, but I'm trying to implement this in Java/Kotlin, though I'm not looking for someone to just give me the magic piece of code that I can just paste and have it working, I'm looking to understand how it can be done better.
Is there a better way to achieve the result I want here?
The solution that worked perfectly for me is the following
angle = -(toDegrees(atan2(y, x)) + 90) % 360
As far as I can see it covers the edge cases.