1

I'm doing some animation on several alpha values and want to set the values relative to a reference value

obj1.alpha = refAlpha + 0.25f;
obj2.alpha = refAlpha + 0.75f;

If refAlpha is 0.5 for example then I want obj2.alpha to be 0.25 not 1.25. What math function is there to do that?

Gruntcakes
  • 37,738
  • 44
  • 184
  • 378
  • why are you asking? is google not working? – Selvin Jul 23 '15 at 17:57
  • Instead of downvoting why not supply the answer as a quick comment. The reason I'm asking is I've looked at the math class but don't see anything, however surely there must be. I could check myself if the value is > 1.0 and adjust, of course I could, but surely there must be a convenience function I can call instead. – Gruntcakes Jul 23 '15 at 17:57
  • No google is not working, that is why I'm asking. Give me the search term to find the answer then. And as I've just said I've just read the math documentaiton. – Gruntcakes Jul 23 '15 at 17:57
  • Now there is an answer, I can reveal I didn't know mod would work on floats. If that's something you don't know its not easy to find out from google. – Gruntcakes Jul 23 '15 at 17:59
  • here you go lazy one: possible duplicate of [How to get the decimal part of a float?](http://stackoverflow.com/questions/5017072/how-to-get-the-decimal-part-of-a-float) – Selvin Jul 23 '15 at 17:59
  • Twat. I'm not lazy, just do not know what to search for. Big difference. – Gruntcakes Jul 23 '15 at 18:01

1 Answers1

2

The mod operator % will do the trick in terms of wrapping. (it works on floats as well as ints).

obj1.alpha = (refAlpha + 0.25f) % 1f
obj2.alpha = (refAlpha + 0.75f) % 1f

public static void main(String[] args) {
  System.out.println(1.25f % 1f); // --> 0.25
}

Unfortunately, java doesn't quite implement mod to the mathematical definition. a % b returns a value in the range (-b, b), as opposed to [0, b). If you are ever subtracting values, the result could therefore be negative. If this is a usecase you are worried about, consider creating a helper function to handle it:

public static float mod(float a, float b){
    return ((a % b) + b) % b;
}

This will make the result in the range [0,b).

Mshnik
  • 7,032
  • 1
  • 25
  • 38