public IEnumerator moveUnitToTargetTile(Vector3 destination) { List <Vector3> path = new List <Vector3>(); Vector3 nextTile = destination; // Create path backwards (going from the destination to the unit's starting position) while (nextTile != currentlySelectedUnit.transform.position) { TileToCheck t = listOfAlreadyCheckedTiles.Find(x => x.pos == nextTile); path.Add(t.pos); nextTile = t.posOfParentTile; } path.Reverse(); int pathIndex = 0; float timeSinceStarted = 0f; float movementSpeed = path.Count * 2f; // Move the unit tile by tile while (pathIndex < path.Count) { // Make the unit move smoothly towards the next tile in the path timeSinceStarted += Time.deltaTime; currentlySelectedUnit.transform.position = Vector3.Lerp(currentlySelectedUnit.transform.position, path[pathIndex], timeSinceStarted * movementSpeed); // If the unit reaches the tile, prepare for the next tile in the path if (currentlySelectedUnit.transform.position == path[pathIndex]) { pathIndex++; timeSinceStarted = 0; } // Go on to next frame8 yield return(null); } // Once the unit finishes the path, stop the coroutine and return control to the cursor activeCursor = true; currentlySelectedUnit.transform.position = destination; // Correct decimal deviations yield break; }
void checkIfTileIsValidForMovement(int posX, int posY, Vector3 parent, int rangeLeft) { Vector3 pos = new Vector3(posX, posY); // Check if the tile has already been explored (FindIndex returns -1 otherwise) if (listOfAlreadyCheckedTiles.FindIndex(x => x.pos == pos) >= 0) { TileToCheck tile = listOfAlreadyCheckedTiles.Find(x => x.pos == pos); if (tile.maxRangeSoFar >= rangeLeft) { return; // Stop exploring, since that path has already been explored before } else // Otherwise, remove the tile (it has an incorrect maxRangeSoFar) { listOfAlreadyCheckedTiles.Remove(tile); } // Then keep exploring (the tile will be readded later) } if (validDestination(posX, posY)) { // Add tile to list of valid targets upperTilemap.SetTile(new Vector3Int(posX, posY, 0), tileSelectorMovement); validTargets.Add(pos); listOfAlreadyCheckedTiles.Add(new TileToCheck(pos, parent, rangeLeft)); // Keep checking if there is still range left if (rangeLeft > 1) { checkValidMovementDestinationsRecursively(posX, posY, rangeLeft - 1); } } else if (allyInTile(posX, posY)) { listOfAlreadyCheckedTiles.Add(new TileToCheck(pos, parent, rangeLeft)); // If the tile is occupied by an ally, the unit cannot move there, but can pass through there if (rangeLeft > 1) { checkValidMovementDestinationsRecursively(posX, posY, rangeLeft - 1); } } }