I am writing a function for a game where I try to place "Path Tiles" from point A to point B.
I wrote a while loop to iterate tiles until I reach point B, I dont know why my loop is not stopping. I had to put a failsafe to make it stop.
I also think the code is very repetitive, so there my be a way to optimize it...
private void RoadBuilder(Vector2 pointA, Vector2 pointB, Image pathTile){
float movingX = pointA.x;
float movingY = pointA.y;
float abDiffX = pointB.x - pointA.x;
float abDiffY = pointB.y - pointA.y;
bool xGo = true;
// Debug.Log(pointA);
// Debug.Log(pointB);
// Debug.Log("Xdiff: "+abDiffX+" Ydiff: "+abDiffY);
int failSafe = 0;
while (movingX != pointB.x || movingY != pointB.y || failSafe != 50)
{
if (abDiffX > 0)
{
if (xGo){
if (movingX != pointB.x) {movingX++;}
xGo = false;
}
else{
if (movingY != pointB.y){
if (abDiffY > 0) {movingY++;}
else {movingY--;}
xGo = true;
}
}
}
else
{
if (xGo){
if (movingX != pointB.x) {movingX--;}
xGo = false;
}
else{
if (movingY != pointB.y){
if (abDiffY > 0) {movingY++;}
else {movingY--;}
}
xGo = true;
}
}
foreach (MapTile tempTile in _mapList)
if (
tempTile.position.x == movingX && tempTile.position.y == movingY
&& tempTile.tileSprite != _tiles[1] && tempTile.tileSprite != _tiles[4]
&& tempTile.position != pointB
) {tempTile.tileSprite = pathTile;}
// Debug.Log("movingX: "+movingX+" movingY: "+movingY);
failSafe++;
}
}
Can anyone tell me what am I doing wrong? or if there is a better way to achive this?
Thanks