Skip to content

Commit

Permalink
Fix distanceSquaredTo (#3365)
Browse files Browse the repository at this point in the history
Fix regression and add tests
  • Loading branch information
oscarcederberg authored Feb 14, 2025
1 parent 14385b3 commit 9875460
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion flixel/math/FlxPoint.hx
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,7 @@ import openfl.geom.Point;
*/
public overload inline extern function distanceSquaredTo(x:Float, y:Float):Float
{
return (this.x - x) * (this.x - x) + (this.y - y) + (this.y - y);
return (this.x - x) * (this.x - x) + (this.y - y) * (this.y - y);
}

/**
Expand Down
39 changes: 39 additions & 0 deletions tests/unit/src/flixel/math/FlxPointTest.hx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,45 @@ class FlxPointTest extends FlxTest
Assert.isTrue(yIsInRange);
}

@Test
function testDistanceTo():Void
{
assertDistanceTo(0, 0, 0, 0, 0);
assertDistanceTo(0, 0, 1, 0, 1);
assertDistanceTo(0, 0, 0, 1, 1);
assertDistanceTo(0, 0, -1, 0, 1);
assertDistanceTo(0, 0, 0, -1, 1);

assertDistanceTo(0, 0, 1, 1, Math.sqrt(2));
assertDistanceTo(0, 0, -1, 1, Math.sqrt(2));
assertDistanceTo(0, 0, 1, -1, Math.sqrt(2));
assertDistanceTo(0, 0, -1, -1, Math.sqrt(2));

assertDistanceTo(3, 4, 0, 0, 5);
assertDistanceTo(-3, -4, 0, 0, 5);
assertDistanceTo(3, 4, -3, -4, 10);

assertDistanceTo(5, 5, 10, 10, Math.sqrt(50));
assertDistanceTo(-5, -5, -10, -10, Math.sqrt(50));

assertDistanceTo(7, -3, -2, 6, Math.sqrt(162));
assertDistanceTo(-7, 3, 2, -6, Math.sqrt(162));
}

function assertDistanceTo(x0, y0, x1, y1, expected:Float):Void
{
point1.set(x0, y0);
point2.set(x1, y1);
FlxAssert.areNear(point1.distanceTo(point2), expected);
FlxAssert.areNear(point2.distanceTo(point1), expected);
FlxAssert.areNear(point1.dist(point2), expected);
FlxAssert.areNear(point2.dist(point1), expected);
FlxAssert.areNear(point1.distanceSquaredTo(point2), expected * expected);
FlxAssert.areNear(point2.distanceSquaredTo(point1), expected * expected);
FlxAssert.areNear(point1.distSquared(point2), expected * expected);
FlxAssert.areNear(point2.distSquared(point1), expected * expected);
}

@Test
function testDegreesBetween():Void
{
Expand Down

0 comments on commit 9875460

Please sign in to comment.