Background: I have 8 images for every sprite in my bird’s view JavaScript game, representing top, top-right, right, right-bottom etc., depending on the player’s space ship speed.
Question: Given the values sprite.speed.x and sprite.speed.y (which could be something like 4 and -2.5, or 2 and 0 for instance), how do I get the correct angle in degrees? Given that angle, I could then have a lookup for which degrees value represents which sprite image. Or perhaps there’s an even easier way. (Currently I’m just using something like “if x below zero use left image” etc. which will result in diagonal images used almost all of the time.)
Searching around, I found …
angle = Math.atan2(speed.y, speed.x);
… but somehow I’m still missing something.
PS: Zero speed can be ignored, these sprites will just use whatever was the last valid direction image.
Thanks so much for any help!
What you suggest is exactly right! Note that the result of Math.atan2 is in radians, and you’re probably more familiar with degrees; you can convert using
angle_degrees = angle*(180./pi).(Note also that you don’t need to normalize as RCIX suggested, though you can if you want to. What you have,
angle = Math.atan2(speed.y, speed.x);, should work just fine.)