Hi,
I am trying to simulate traffic in Unity3d. I have got a waypoint based system and I am currently trying to implement obstacle avoidance. I have done this before for opponents in racing games, but using raycasts. My current OA system for the traffic uses three box triggers, and here is the code:
using UnityEngine;
using System.Collections;
public class TSFrontDetector : MonoBehaviour
{
public bool detected;
public TSVehicleController controller;
public TSLeftDetector leftDetector;
public TSRightDetector rightDetector;
IEnumerator OnTriggerStay(Collider other)
{
controller.overrideInput = true;
detected = true;
TSVehicleController otherController = other.GetComponent<TSVehicleController>();
if (otherController != null) {
if (otherController.atTrafficLight || (leftDetector.detected && rightDetector.detected)) {
controller.atTrafficLight = otherController.atTrafficLight;
controller.steerInput = 0;
controller.motorInput = 0;
controller.brakeInput = 1;
return null;
}
else
return AvoidObstacle();
}
else
return AvoidObstacle();
}
void OnTriggerExit(Collider other)
{
detected = false;
controller.overrideInput = false;
}
IEnumerator AvoidObstacle()
{
controller.brakeInput = 1;
yield return new WaitForSeconds(10); //TODO: Add variable controlled by TSDetectorManager.
controller.motorInput = -1f;
controller.brakeInput = 0;
if (leftDetector.detected)
controller.steerInput = -1;
else
controller.steerInput = 1;
yield return new WaitForSeconds(1);
controller.motorInput = 1;
controller.brakeInput = 0;
if (leftDetector.detected)
controller.steerInput = 1;
else
controller.steerInput = -1;
}
}
The problem I am facing is that the AI successfully stops for a few seconds (ie the statements before the first WaitForSeconds), but after that, the AI behaves erratically and continuously switches between the code before the second WaitForSeconds and the code after it. leftDetector and rightDetector have a box trigger on them, which makes their bool detected true during OnTriggerStay and false in OnTriggerExit. So my question is this: I will be having quite a few AI traffic vehicles (around 50 average) per scene. I can successfully simulate this OA behaviour with 3 raycast without yield statements. For performance, which is better? 3 raycasts (having distance around 20) or 3 box colliders? I can also manage a method with 1 raycast and 2 box colliders (without the yield statement). If raycasts are too heavy on the cpu, are there any other alternatives? Or can the above code be fixed?
Thanks!