0

I am writing a game in HTML5 and having problems with a piece of Javascript to do with the conversion of radians to degrees.

Currently my sprite is turned when the left and right keys on the keyboard are pressed/held down. The framework I am using outputs the rotation value in radians however the number can go above/below 1 and -1. Each time the right key applies a +0.05 to the rotation value and -0.05 from the left key.

Everything works fine when I constantly rotate clockwise (right key) using the following code:

game.player.rotationdeg = (ship.rotation * (180/Math.PI)) % 360;

Even if I go through a full rotation over 360 degrees the resulting degrees start back at 0 and continues to provide the correct angle.

When I go counter clockwise and the rotation value goes below 0 then things go out of whack. Instead of 270 degrees I get -90. This is causing me a lot of time and stress and I would appreciate any assistance.

I believe I might be able to check if the result is a negative and then just minus it from 360 but I am unsure of where to put that in the code I have or if it needs a separate function to work it out. I believe it might just be a problem with how I am approaching the situation.

10
  • 1
    Additional info: the radian value can go up to high numbers say 20 for example, it will return the correct degrees ignoring how many full rotations there are in radians with the code I have posted. Commented Apr 12, 2015 at 10:32
  • 2
    From what I understand, that's the issue the question is describing (that the result from JavaScript is negative), The answers provide the correct behaviour as far as I'm aware. Commented Apr 12, 2015 at 10:43
  • 1
    Yes, that will work. If you'd like you could put it into a separate function, but that's not necessary. Try that where ship.rotation === -0.5 * pi Commented Apr 12, 2015 at 10:58
  • 1
    Thank you friend. If you post this as an answer I would like to show my appreciation but if you feel it is a true duplicate I will delete my original post. Commented Apr 12, 2015 at 11:00
  • 1
    To be honest this feels a bit too much of a duplicate to answer for me, but take an upvote. Commented Apr 12, 2015 at 11:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.