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 3 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
17 changes: 17 additions & 0 deletions flixel/math/FlxMath.hx
Original file line number Diff line number Diff line change
Expand Up @@ -573,4 +573,21 @@ class FlxMath
{
return (n > 0) ? n : -n;
}

/**
* Performs a modulo operation on two numbers.
cyn0x8 marked this conversation as resolved.
Show resolved Hide resolved
* This function differs from the built-in `%` operator in that it always
* returns a positive result even with negative numbers involved.
* For example, `-5 % 3` would return `-2` (truncated division),
* while `mod(-5, 3)` would return `1` (Euclidean division).
*
* @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