From 667403b3341dacdb1a0f78a068fb308ba62b59a1 Mon Sep 17 00:00:00 2001 From: Martin Felis Date: Sun, 16 Jul 2023 22:00:17 +0200 Subject: [PATCH] Better conversion between texture and offset coords. --- scenes/TileWorld.cs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/scenes/TileWorld.cs b/scenes/TileWorld.cs index 900a10e..4dbb2d0 100644 --- a/scenes/TileWorld.cs +++ b/scenes/TileWorld.cs @@ -250,7 +250,7 @@ public class TileWorld : Spatial int assetIndex = randomGenerator.Next(assets.Count); Spatial assetInstance = (Spatial)assets[assetIndex].Duplicate(); Transform assetTransform = Transform.Identity; - assetTransform.origin = GetTileWorldCenterFromOffset(offsetCoord); + assetTransform.origin = GetHexCenterFromOffset(offsetCoord); assetTransform.origin.y += 1.2f; assetTransform.basis = assetTransform.basis.Rotated(Vector3.Up, (float)(randomGenerator.NextDouble() * Mathf.Pi * 2)); @@ -275,13 +275,14 @@ public class TileWorld : Spatial Random environmentRandom = new Random(Seed); Colormap.Lock(); - foreach (int coord_x in Enumerable.Range(0, Size)) + foreach (int textureCoordU in Enumerable.Range(0, Size)) { - foreach (int coord_y in Enumerable.Range(0, Size)) + foreach (int textureCoordV in Enumerable.Range(0, Size)) { - Vector2 offsetCoord = new Vector2(coord_x, coord_y); - Color colorValue = Colormap.GetPixel(coord_x, coord_y); - HexCell cell = HexCell.FromOffsetCoords(offsetCoord - Vector2.One * _halfSize); + Color colorValue = Colormap.GetPixel(textureCoordU, textureCoordV); + Vector2 textureCoord = new Vector2(textureCoordU, textureCoordV); + HexCell cell = TextureCoordToCell(textureCoord); + Vector2 offsetCoord = cell.OffsetCoords; if (IsColorEqualApprox(colorValue, RockColor)) { @@ -306,7 +307,8 @@ public class TileWorld : Spatial Entities.AddChild(treeAsset); HexGrid.AddObstacle(cell); } - } else if (IsColorWater(colorValue)) + } + else if (IsColorWater(colorValue)) { HexGrid.AddObstacle(cell); } @@ -411,7 +413,8 @@ public class TileWorld : Spatial public Vector2 WorldToOffsetCoords(Vector3 worldCoord) { - return HexGrid.GetHexAt(new Vector2(worldCoord.x, worldCoord.z)).OffsetCoords + Vector2.One * Mathf.Round(Size / 2f); + return HexGrid.GetHexAt(new Vector2(worldCoord.x, worldCoord.z)).OffsetCoords + + Vector2.One * Mathf.Round(Size / 2f); } public Vector3 GetTileWorldCenterFromOffset(Vector2 offsetCoord) @@ -426,4 +429,14 @@ public class TileWorld : Spatial Vector2 tileCenter = HexGrid.GetHexCenterFromOffset(offsetCoord); return new Vector3(tileCenter.x, GetHeightAtOffset(offsetCoord), tileCenter.y); } + + public HexCell TextureCoordToCell(Vector2 textureCoord) + { + return HexCell.FromOffsetCoords(textureCoord - Vector2.One * _halfSize); + } + + public Vector2 TextureCoordToOffsetCoord(Vector2 textureCoord) + { + return TextureCoordToCell(textureCoord).OffsetCoords; + } } \ No newline at end of file