how to create a whirling search loop, with 3 for…loop,
haven’t find any reference for this on internet may be I using the wrong keyword, so… here the thing I created.
public bool FindFreeSpace(Vector3 point, int searchRange, out Vector3 location)
{
// init checker
GameObject fakeObject = new GameObject();
StructureController checker = fakeObject.AddComponent<StructureController>();
// your controller should return the space is available or not.
/*********************
// loop pattern from range 1~5
[5][5][5][5][5][5]
[5][3][3][3][3]
[5][3][1][1][4]
[5][3][1][2][4]
[5][2][2][2][4]
[4][4][4][4][4]
*********************/
int range = searchRange;
int dir = 1; // -1/1
float session = 0f; // record next cycle start point, e.g. Vector2(session,session) , x == z
float baseX = checker.transform.localPosition.x;
float baseY = checker.transform.localPosition.y;
float baseZ = checker.transform.localPosition.z;
bool found = false;
for (int r = 1; !found && r <= range; r++ )
{
int x = 0;
int z = 0;
for (x = 0; !found && (dir == 1 && x < r) || (dir == -1 && x > -r); x += dir)
{
// move x relative 0~r or 0~-r
if (found = MoveChecker(checker, new Vector3(baseX + session + (float)x, baseY, baseZ + session + (float)z))) break;
}
for (z = 0; !found && (dir == 1 && z < r) || (dir == -1 && z > -r); z += dir)
{
// move z relative 0~r or 0~-r
if (found = MoveChecker(checker, new Vector3(baseX + session + (float)x, baseY, baseZ + session + (float)z))) break;
}
session += (float)(dir * r); // next cycle start point.
dir *= -1; // change direction
}
// update output variable
if (found)
location = checker.transform.localPosition;
else
location = point;
GameObject.DestroyImmediate(fakeObject);
return found;
}