From 98754604b0b24a18d6dd0a89b849fa298c38bf2a Mon Sep 17 00:00:00 2001 From: Oscar Cederberg <44801604+oscarcederberg@users.noreply.github.com> Date: Fri, 14 Feb 2025 19:47:39 +0100 Subject: [PATCH] Fix distanceSquaredTo (#3365) Fix regression and add tests --- flixel/math/FlxPoint.hx | 2 +- tests/unit/src/flixel/math/FlxPointTest.hx | 39 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/flixel/math/FlxPoint.hx b/flixel/math/FlxPoint.hx index 3a2157aedc..7f6fdd54c0 100644 --- a/flixel/math/FlxPoint.hx +++ b/flixel/math/FlxPoint.hx @@ -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); } /** diff --git a/tests/unit/src/flixel/math/FlxPointTest.hx b/tests/unit/src/flixel/math/FlxPointTest.hx index b7dd865926..a7ee415e82 100644 --- a/tests/unit/src/flixel/math/FlxPointTest.hx +++ b/tests/unit/src/flixel/math/FlxPointTest.hx @@ -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 {