public void EnterFindTreeState() { //Check if no trees, exit out of the map if (MapManager.Instance.m_TreeOnMap.Count <= 0) { ChangeState(States.GET_OUT_OF_MAP); return; } if (m_Animator != null) { m_Animator.SetTrigger("Walking"); m_Animator.ResetTrigger("Chased"); } //check if prev tree is still avilable if (m_NearestTree != null) { if (!m_NearestTree.m_Dead) { m_Destination = MapManager.Instance.GetGridPosToWorld(m_NearestTree.m_PlantGridPos); m_Dir = (m_Destination - (Vector2)transform.position); m_Dir.Normalize(); return; } } Vector2Int m_CurrentGridPos = MapManager.Instance.GetWorldToGridPos(transform.position); //the nearest tree float closestDist = Mathf.Infinity; Vector2Int treeDestination = Vector2Int.zero; foreach (KeyValuePair <Vector2Int, PlantTree> tree in MapManager.Instance.m_TreeOnMap) { float dist = Vector2.SqrMagnitude(tree.Key - m_CurrentGridPos); if (dist < closestDist) { if (tree.Value.m_Dead) { continue; } closestDist = dist; m_NearestTree = tree.Value; treeDestination = tree.Key; //if the dist is already in a certain radius, just stop if (dist < m_MinNoOfGrid * m_MinNoOfGrid) { break; } } } m_Destination = MapManager.Instance.GetGridPosToWorld(treeDestination); m_Dir = (m_Destination - (Vector2)transform.position); m_Dir.Normalize(); }
public float Plant(Vector2Int tilePos) { //gets a random available plant type Inventory inventory = GameStats.Instance.m_Inventory; Plant_Types type = GameStats.Instance.GetAvilablePlantType(); bool isTree = type < Plant_Types.FLOWERS; if (!inventory.HaveInInventory(type)) { return(0.0f); } if (isTree) { if (m_TreeOnMap.ContainsKey(tilePos)) { return(0.0f); } //plant tree GameObject treeObj = m_PlantManager.GetAndSpawnTree(); if (treeObj == null) { return(0.0f); } treeObj.transform.position = m_MapGrid.GetCellCenterWorld((Vector3Int)tilePos); treeObj.SetActive(true); PlantTree plantTree = treeObj.GetComponent <PlantTree>(); if (plantTree) { m_PlantManager.InitType(type, tilePos, plantTree); m_TreeOnMap.Add(tilePos, plantTree); inventory.RemoveOneFromInventory(type); //remove one from inventory GameStats.Instance.UpdateCurrentPlantNumber(isTree, m_TreeOnMap.Count); return(plantTree.m_PlantTime); } } else { if (m_PlantOnMap.ContainsKey(tilePos)) { return(0.0f); } //plant plants GameObject plantObj = m_PlantManager.GetAndSpawnPlant(); if (plantObj == null) { return(0.0f); } plantObj.transform.position = m_MapGrid.GetCellCenterWorld((Vector3Int)tilePos); plantObj.SetActive(true); Plant plantedPlant = plantObj.GetComponent <Plant>(); if (plantedPlant) { m_PlantManager.InitType(type, tilePos, plantedPlant); m_PlantOnMap.Add(tilePos, plantedPlant); inventory.RemoveOneFromInventory(type); //remove one from inventory GameStats.Instance.UpdateCurrentPlantNumber(isTree, m_PlantOnMap.Count); return(plantedPlant.m_PlantTime); } } return(0.0f); }