Hey all, need some help with finding the best way to find the triangle that a given point occupies. The reason for this is that my terrain is made up of groups of four triangles that when combined form a square (this is necessary to achieve the visual style I want for the terrain). Here’s a picture example of a single square:
Each of these four triangles can have their own values, so for example the left and top triangles can be water while the right and bottom triangles are land. Because of this I need to be able to tell what triangle a point is within. Once I know whether it’s the left, top, right, or bottom triangle I can then pull that data.
My first thought was to find the distance between the point and the centers of all four triangles, and then compare them to find the triangle with the shortest distance. There’s some preliminary code below if it helps at all. Note: I will be “manually” calculating the distance instead of using Vector2.Distance if I decide to go this route.
If anyone has other ideas please let me know!
LeftTriPositionOffset = new Vector2 (0.25f, 0.5f);
TopTriPositionOffset = new Vector2 (0.5f, 0.75f);
RightTriPositionOffset = new Vector2 (0.75f, 0.5f);
BottomTriPositionOffset = new Vector2 (0.5f, 0.25f);
arrayPositionX = (int)(worldPosition.x / HSpacing);
arrayPositionY = (int)(worldPosition.y / HSpacing);
leftTriDistance = Vector2.Distance (worldPosition + LeftTriPositionOffset, worldPosition);
topTriDistance = Vector2.Distance (worldPosition + TopTriPositionOffset, worldPosition);
rightTriDistance = Vector2.Distance (worldPosition + RightTriPositionOffset, worldPosition);
bottomTriDistance = Vector2.Distance (worldPosition + BottomTriPositionOffset, worldPosition);
if (leftTriDistance <= topTriDistance && leftTriDistance <= rightTriDistance && leftTriDistance <= bottomTriDistance) {
arrayPositionX += (int)(LeftTriArrayOffset.x);
arrayPositionY += (int)(LeftTriArrayOffset.y);
}
else if (topTriDistance <= leftTriDistance && topTriDistance <= rightTriDistance && topTriDistance <= bottomTriDistance) {
arrayPositionX += (int)(TopTriArrayOffset.x);
arrayPositionY += (int)(TopTriArrayOffset.y);
}
else if (rightTriDistance <= leftTriDistance && rightTriDistance <= topTriDistance && rightTriDistance <= bottomTriDistance) {
arrayPositionX += (int)(RightTriArrayOffset.x);
arrayPositionY += (int)(RightTriArrayOffset.y);
}
else if (bottomTriDistance <= leftTriDistance && bottomTriDistance <= topTriDistance && bottomTriDistance <= rightTriDistance) {
arrayPositionX += (int)(BottomTriArrayOffset.x);
arrayPositionY += (int)(BottomTriArrayOffset.y);
}
else {
Debug.LogError ("Cannot locate a Tri that is closest to position " + worldPosition + ".");
}
terrainTriArrayPosition = arrayPositionX * TerrainTriYSize + arrayPositionY;