Public Group

# keep value within the range of radians

This topic is 3656 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

My current code:
if (x < -PI)
x += TWOPI;
else
if (x >  PI)
x -= TWOPI;

The problem: x could be 400.0 or more, under those circumstances this wrapping method fails. I need to keep x in the radian range, always. Any ideas? Thanks

##### Share on other sites
The best answer may depend on the language...

##### Share on other sites
Really? that's just pseudo code in fact. I'm coding in C++. I just drew a blank and I can't think of any good way of doing this...

Right now I'd have to apply the aforementioned statement on each update instead of every now and then (when I actually do require X to be in that range). It's a small piece of code and it won't kill any performance at all I was just wondering though if there could be a better way of doing it.

##### Share on other sites
Modular arithmetic is an alternative.

##### Share on other sites
How would you go about using modulo (fmod as suggested) when the variable starts on -PI and ends as PI ? (full range) -- take a look at my pseudo code to see what I mean.

##### Share on other sites
  x = fmod(x, TWO_PI);  if (x > PI) x -= TWO_PI

##### Share on other sites
Quote:
 Original post by gussoReally?
Absolutely, imagine if you'd picked a language that has a wrapping function already [smile]

Quote:
 I'm coding in C++. I just drew a blank and I can't think of any good way of doing this...
This is a common and fairly unsophisticated solution:

template <typename T>T wrap(T value, T lower, T upper){    T r = upper - lower;    while (upper < value) value -= r;    while (value < lower) value += r;    return value;}// ...x = wrap(x, -PI, PI);

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 14
• 14
• 45
• 22
• 27
• ### Forum Statistics

• Total Topics
634044
• Total Posts
3015211
×