private TrafficLightBehavior DetectTrafficLight() { RaycastHit hit; float minDist = Mathf.Infinity; TrafficLightBehavior nearestTrafficLight = null; foreach (TrafficLightBehavior trafficLight in trafficLights) { Vector3 screenPoint = Camera.main.WorldToScreenPoint(trafficLight.transform.position); Ray ray = Camera.main.ScreenPointToRay(screenPoint); if (Physics.Raycast(ray, out hit)) { float dist = Vector3.Distance(transform.position, trafficLight.transform.position); if (dist < minDist) { minDist = dist; nearestTrafficLight = trafficLight; } } } return(nearestTrafficLight); }
private float CaculateSpeed(float roadAngle) { TrafficLightBehavior trafficLight = DetectTrafficLight(); GameObject obstacle = NearestObstacle(); roadAngle = Mathf.Abs(roadAngle); Debug.Log("Angle: " + roadAngle); float offsetObstacle = Mathf.Infinity; if (obstacle != null) { offsetObstacle = Vector3.Distance(obstacle.transform.position, transform.position); } float offsetTrafficLight = Mathf.Infinity; if (trafficLight != null) { offsetTrafficLight = Vector3.Distance(trafficLight.transform.position, transform.position); } if (obstacle == null && trafficLight == null) { //Debug.Log("Both"); return(0.3f); } bool isLight = offsetTrafficLight < offsetObstacle ? true : false; if (offsetTrafficLight < offsetObstacle) { Debug.Log("TrafficLight " + offsetTrafficLight); Debug.Log(roadAngle); object[] lightStatus; switch (trafficLight.lightColor) { case (TrafficLightBehavior.LightColor.GREEN_LIGHT): { lightStatus = new object[2] { "Green", (double)trafficLight.countDown }; break; } case (TrafficLightBehavior.LightColor.YELLOW_LIGHT): { lightStatus = new object[2] { "Yellow", (double)trafficLight.countDown }; break; } case (TrafficLightBehavior.LightColor.RED_LIGHT): { lightStatus = new object[2] { "Red", (double)trafficLight.countDown }; break; } default: { lightStatus = new object[2] { "Green", trafficLight.countDown }; break; } } Debug.Log(lightStatus[0]); float speed = (float)Program.CalculateSpeed(true, offsetTrafficLight, roadAngle, lightStatus); Debug.Log("speed: " + speed); if (speed < 2) { speed = 0f; } return(speed / (120f / 0.3f)); } else { //Debug.Log("Obstacle"); float speed = (float)Program.CalculateSpeed(false, offsetObstacle, roadAngle, null); Debug.Log("speed: " + speed); return(speed / (120f / 0.2f)); } }