protected void PathFind(int x, int y) { // Pathfind to player CellGrid cellGrid = LevelGen.CellGrid; GridCell targetCell = cellGrid.Grid[x, y]; GridCell currentCell = cellGrid.GetCellAtPos(transform.position); List <Vector3> path = cellGrid.FindPathWorld(targetCell, currentCell); if (path.Count > 1) { // Move towards next cell Vector3 dir = (path[1] - transform.position).normalized; TurnTowards(dir); Move(dir); } }
// Handle states and pathfinding protected override void Update() { Debug.Log("Current state: " + currentState); lineVertices = 0; // Call base update method base.Update(); // Get current node GridCell currentCell = cellGrid.GetCellAtPos(transform.position); PathNode oldNode = currentNode; currentNode = cellGrid.GetPathfindingNode(currentCell); // Common update stuff // Do visibility testing TestVisibility(); // Look for powerups and collect them if we can see them Vector3 powerupPos; if (currentState != State.ATTACK_PLAYER && currentState != State.LOOK_FOR_PLAYER) { if (CanSeeObjectOnLayer(FacingDirection, powerupLayer, "Powerup", out powerupPos)) { Vector3 dir = (powerupPos - transform.position).normalized; Move(dir); TurnTowards(dir); } } // Set default movement speed (later gets replaced in state handlers) targetMovementSpeed = DEFAULT_MOVE_SPEED; // Handle states // Return early if the state handler returns false switch (currentState) { case State.MAP_LEVEL: if (!MapLevel()) { return; } break; case State.PATROL_LEVEL: if (!PatrolLevel()) { return; } break; case State.ATTACK_PLAYER: if (!AttackPlayer()) { return; } break; case State.LOOK_FOR_PLAYER: if (!LookForPlayer()) { return; } break; default: Debug.LogError("NonplayerCharacter: invalid state reached"); return; } // Follow path if there is one if (currentPath != null) { // Remove current node from path if (currentPath.Contains(currentNode)) { currentPath.Remove(currentNode); } // Clear path if empty if (currentPath.Count == 0) { currentPath = null; } else { // Get last node in path PathNode lastNode = currentPath.Last(); // Walk the path if it's still not null if (currentPath != null) { // Walk path if not empty PathNode nextNode = currentPath[0]; // Get current state of cell CellState state = cellStates[(int)nextNode.Position.x, (int)nextNode.Position.y]; // If blocked, clear the path if (state == CellState.BLOCKED) { currentPath = null; } else { // Move towards next node in path Vector3 dir = (nextNode.Position - currentNode.Position).normalized; movementDir = dir; Move(dir * targetMovementSpeed); } } } } // Reset state just changed flag stateJustChanged = false; }