Skip to content

Commit

Permalink
add "mod" function to FlxMath (#3341)
Browse files Browse the repository at this point in the history
* add mod function

* add mod test

* update mod docs

* update mod docs 2
  • Loading branch information
cyn0x8 authored Jan 28, 2025
1 parent 1272a65 commit a7dcc5c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
19 changes: 19 additions & 0 deletions flixel/math/FlxMath.hx
Original file line number Diff line number Diff line change
Expand Up @@ -573,4 +573,23 @@ class FlxMath
{
return (n > 0) ? n : -n;
}

/**
* Performs a modulo operation to calculate the remainder of `a` divided by `b`.
*
* The definition of "remainder" varies by implementation;
* this one is similar to GLSL or Python in that it uses Euclidean division, which always returns positive,
* while Haxe's `%` operator uses signed truncated division.
*
* For example, `-5 % 3` returns `-2` while `FlxMath.mod(-5, 3)` returns `1`.
*
* @param a The dividend.
* @param b The divisor.
* @return `a mod b`.
*/
public static inline function mod(a:Float, b:Float):Float
{
b = Math.abs(b);
return a - b * Math.floor(a / b);
}
}
12 changes: 12 additions & 0 deletions tests/unit/src/flixel/math/FlxMathTest.hx
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,16 @@ class FlxMathTest extends FlxTest
// #2126
Assert.areEqual(1521730678.942, FlxMath.roundDecimal(1521730678.942, 3));
}

@Test
function testMod()
{
Assert.areEqual(0, FlxMath.mod(8, 4));
Assert.areEqual(3, FlxMath.mod(8, 5));
Assert.areEqual(0.355, FlxMath.mod(0.941, 0.586));
Assert.areEqual(1, FlxMath.mod(-5, 3));
Assert.areEqual(1, FlxMath.mod(-5, -3));
Assert.areEqual(0.128, FlxMath.mod(-0.834, 0.481));
Assert.areEqual(2.5, FlxMath.mod(9, -6.5));
}
}

0 comments on commit a7dcc5c

Please sign in to comment.