Hi all.
I’m working on a project at the moment which is a turn-based strategy game on a hex grid, and having some trouble trying to find the closest hex to align buildings and such when trying to place them.
This is the code I have at the moment:
public IEnumerator AdjustBuildingPlacement (Vector3 pointA, Vector3 pointB, float time) {
if(!isMoving) {
isMoving = true;
FindNearestTile();
float t = 0f;
while (t < 1f) {
t += Time.deltaTime / time;
transform.position = Vector3.Lerp(transform.position, nearest.position, t);
yield return 0;
}
isMoving = false;
}
}
public Transform FindNearestTile() {
Collider[] tilesNearby = Physics.OverlapSphere(transform.position, 0.5f);
foreach (Collider hit in tilesNearby) {
if (hit.tag == "HexTile") {
Debug.DrawLine(transform.position, hit.transform.position, Color.red, 5);
float dist = Vector3.Distance(transform.position, hit.transform.position);
if (dist < minDist) {
minDist = dist;
}
}
nearest = hit.transform;
}
tilesNearby = null;
return nearest;
}
The problem is that the object moves to the closest hex tile in the negative x/z axes, even if there is a closer hex tile in the positive x/z axes. It should move to the closest hex tile regardless of direction, but it always moves to the closest hex tile downwards & left (negative on the x/z axes). I can see which is closer, and the Debug.DrawLine shows it clearly.
Hopefully somebody can help me with this!
Thanks in advance!