Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add "mod" function to FlxMath #3341

Merged
merged 4 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
}
}
Loading