EDIT: I have an angle from using Math.atan2() which I then want to add or subtract values from. However, this addition and subtraction sometimes means the angle is greater that pi or less than -pi and I’m looking for a way to get one of these outside angles back into the correct range.
I’m trying to find a value mod 2pi in JavaScipt using the following code:
foo % Math.PI * 2;
However, it always just returns foo, even if I try this:
var bar = Math.PI * 2; foo % bar;
Can anyone explain to me why this doesn’t work?
DLiKS
Advertisement
Answer
You aren’t making an assignment:
foo = foo % Math.PI * 2;
Or:
foo %= Math.PI * 2;
EDIT:
To paraphrase your updated question, you have a value foo, which may be any angle, however you want foo to be in the range [-pi,pi]. You need to do this programatically:
foo %= 2 * Math.PI; // Now in the range [-2pi,2pi] if (Math.abs(foo) > Math.PI) { foo -= 2 * Math.PI * Math.sign(foo); }