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:
JavaScript
x
2
1
foo % Math.PI * 2;
2
However, it always just returns foo, even if I try this:
JavaScript
1
3
1
var bar = Math.PI * 2;
2
foo % bar;
3
Can anyone explain to me why this doesn’t work?
DLiKS
Advertisement
Answer
You aren’t making an assignment:
JavaScript
1
2
1
foo = foo % Math.PI * 2;
2
Or:
JavaScript
1
2
1
foo %= Math.PI * 2;
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:
JavaScript
1
6
1
foo %= 2 * Math.PI; // Now in the range [-2pi,2pi]
2
3
if (Math.abs(foo) > Math.PI) {
4
foo -= 2 * Math.PI * Math.sign(foo);
5
}
6