IEnumerator WaitAtCrossRoad(CrossRoad crossRoad) { executingCoroutine = true; currentSpeed = 0; while (crossRoad.IsRoadOccupied(gameObject.GetInstanceID())) { yield return(new WaitForSeconds(0.5f)); // What if two cars enter at the same time } currentSpeed = maxSpeed; executingCoroutine = false; }
private GameObject DetectRoadAhead() { GameObject objectFound = null; Vector3 roadDectector = transform.forward * DETECTION_DISTANCE; Vector3 fromDetector = transform.position + new Vector3(0, 2.8f, 3); roadDectector.y -= 0.7f;; RaycastHit hit; Ray drivingRay = new Ray(transform.position + new Vector3(0, 2f, 0), roadDectector); Debug.DrawRay(transform.position + new Vector3(0, 2f, 0), roadDectector * 8, Color.yellow); if (Physics.Raycast(drivingRay, out hit, 20, roadDetectorLayer)) // TODO chequear solo el suelo { objectFound = hit.transform.gameObject; if (objectFound.GetComponent <CrossRoad>() != null) { if (!executingCoroutine) // TO-DO check to move this to function level somehow { CrossRoad crossRoad = objectFound.GetComponent <CrossRoad>(); logger.Log(transform.name + "Found a crossroad, taking decisions."); if (crossRoad.IsRoadOccupied(gameObject.GetInstanceID())) { // Coroutine to wait and mark as turning logger.Log("Stopping at road cross a vehicle is crossing"); StartCoroutine(WaitAtCrossRoad(crossRoad)); } else { // Choose to go straight, left or right CrossRoad.DIRECTION_FROM directionFrom = GetMyDirectionFrom(); List <CrossRoad.DIRECTION_FROM> possibleDirections = crossRoad.GetPossibleDirections(directionFrom); int randomChoose = UnityEngine.Random.Range(0, possibleDirections.Count); CrossRoad.DIRECTION_FROM directionTo = possibleDirections[randomChoose]; TURN turn = GetTurn(directionFrom, directionTo); switch (turn) { case TURN.STRAIGHT: // Go straight logger.Log("Continuing straight"); StartCoroutine(CrossStraight(crossRoad)); break; case TURN.LEFT: // Turn left logger.Log("Lets go left"); StartCoroutine(GoLeft(crossRoad)); break; case TURN.RIGHT: // Turn right logger.Log("Lets go right"); StartCoroutine(GoRight(crossRoad)); break; case TURN.BACK: // Turn back: THIS IS NOT ALLOWED AS CROSS TAKES OUT THE ORIGIN logger.Log("Found a wall doing a 180 turn."); StartCoroutine(MakeUTurnOnCross(crossRoad)); break; default: // Go straight logger.Log("[Default] Continuing straight"); StartCoroutine(CrossStraight(crossRoad)); break; } } } } if (objectFound.CompareTag("Wall")) { if (!executingCoroutine) { logger.Log("Found a wall doing a 180 turn."); StartCoroutine(TurnBack()); } } } return(objectFound); }