/// <summary> /// Function to find a path between a starting position and a grid entity /// </summary> /// <param name="startPos">starting position</param> /// <param name="entity">target entity</param> /// <returns>Queue containing the nodes an entity shall traverse</returns> public Queue <IPath> FindPath(Vector3 startPos, IGridEntity entity) { var cels = entity.OccupyingCels; List <IPath> neighbours = new List <IPath>(); foreach (IPath cel in cels) { neighbours.AddRange(GetNeighbours(cel)); } float distance = Mathf.Infinity; Vector3 targetPos = Vector3.zero; foreach (var neighbour in neighbours) { // TODO: Consider neighbour state // if (neighbour.celState != IPathState.Walkable) // continue; if (Vector3.Distance(neighbour.WorldPos, startPos) < distance) { distance = Vector3.Distance(neighbour.WorldPos, startPos); targetPos = neighbour.WorldPos; } } return(FindPath(startPos, targetPos)); }
static IEnumerable <Transform> LazyGetChildren(Transform parent) { foreach (Transform child in parent) { IGridEntity entidad = child.GetComponentInChildren <IGridEntity>(); if (entidad != null) { yield return(child); } } }
/// <summary> /// Actualiza la posicion de una entidad dentro de la grilla. /// </summary> /// <param name="entity">La entidad que va a calcular su posición en la grilla</param> public void UpdateEntityPosition(IGridEntity entity) { MonoBehaviour.print(entity + " its moving..."); //Chequeamos la posicion actual de la entidad y si hay un registro anterior de el, de lo contrario su registro sera "afuera" Vector2 lastPos = _lastPositions.ContainsKey(entity) ? _lastPositions[entity] : outside; Vector2 currentPos = GetPositionInGrid(entity.positionInWorld); //Misma posición, no necesito hacer nada if (lastPos == currentPos) { MonoBehaviour.print(entity + " Position its the same, no action required."); return; } //Si la nueva posición cambio y esta dentro de la grilla... bool toChange = IsInsideGrid(currentPos); if (toChange) { //Lo "sacamos" de la celda anterior si la posición estaba dentro de la grilla. if (lastPos != outside) { _buckets[(int)lastPos.x, (int)lastPos.y].Remove(entity); } //Lo "metemos" a la celda nueva, o lo sacamos si salio de la grilla _buckets[(int)currentPos.x, (int)currentPos.y].Add(entity); _lastPositions[entity] = currentPos; MonoBehaviour.print(entity + " Position has been actualized, last position was: " + lastPos + " and his new position its: " + currentPos); } else //Esta afuera de la grilla { MonoBehaviour.print(entity + " Its outside of the Grid. "); _lastPositions.Remove(entity); } }