From 1e7e07f349a61fda172d6741a2c8043651b574f2 Mon Sep 17 00:00:00 2001 From: Martin Felis Date: Wed, 30 Aug 2023 08:53:49 +0200 Subject: [PATCH] Fixed infinite loop when querying CellsForLine. --- HexGrid.cs | 9 ++++++--- tests/HexGridTests.cs | 11 +++++++++++ tests/NavigationComponentTests.cs | 12 ------------ 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/HexGrid.cs b/HexGrid.cs index c6a3060..1de91f0 100644 --- a/HexGrid.cs +++ b/HexGrid.cs @@ -294,10 +294,12 @@ public class HexGrid : Resource List result = new List(); HexCell toCell = GetHexAt(toPlane); - Vector2 direction = (toPlane - fromPlane).Normalized(); + float distance = (toPlane - fromPlane).Length(); + Vector2 direction = (toPlane - fromPlane) / distance; Vector2 currentPointPlane = fromPlane; HexCell currentCell = GetHexAt(currentPointPlane); + float currentDistance = 0; do { @@ -311,8 +313,9 @@ public class HexGrid : Resource out boundaryPlaneDistance); currentCell = currentCell.GetAdjacent(HexCell.NeighborDirections[neighbourIndex]); - currentPointPlane += direction * boundaryPlaneDistance * 1.001f; - } while (currentCell != toCell); + currentDistance += boundaryPlaneDistance * 1.001f; + currentPointPlane = fromPlane + direction * boundaryPlaneDistance; + } while (currentDistance < distance); result.Add(currentCell); diff --git a/tests/HexGridTests.cs b/tests/HexGridTests.cs index 8cbfc12..9275e5b 100644 --- a/tests/HexGridTests.cs +++ b/tests/HexGridTests.cs @@ -88,4 +88,15 @@ public class HexGridTests : TestClass Assert.Equal(HexCell.FromOffsetCoords(new Vector2(1, -1)), lineCells[1]); Assert.Equal(HexCell.FromOffsetCoords(new Vector2(2, 0)), lineCells[2]); } + + [Test] + public void GetTestsInfiniteLoop() + { + HexGrid grid = new HexGrid(); + + Vector2 fromPlane = new Vector2(-2.31678f, -5.024752f); + Vector2 toPlane = new Vector2(-2.599937f, -6.134028f); + + List cellList = grid.GetCellsForLine(fromPlane, toPlane); + } } \ No newline at end of file diff --git a/tests/NavigationComponentTests.cs b/tests/NavigationComponentTests.cs index b7c8e8f..b9108e8 100644 --- a/tests/NavigationComponentTests.cs +++ b/tests/NavigationComponentTests.cs @@ -28,16 +28,4 @@ public class NavigationComponentTests : TestClass _navigationComponent = new NavigationComponent(); _navigationComponent.TileWorld = _tileWorld; } - - [Test] - public void SimpleTest() - { - _tileWorld.HexGrid.AddObstacle(HexCell.FromOffsetCoords(new Vector2 (-4, 7))); - - Vector3 startPoint = new Vector3(-2.25f, 1.2f, -4.76314f); - Vector3 endPoint = new Vector3(-2.533157f, 1.2f, -5.872417f); - - bool isBlocked = _navigationComponent.CheckSweptTriangleCellCollision(startPoint, endPoint, 0.27f); - } - } \ No newline at end of file