- Home /
How to make vehicles sense and obey traffic lights?
I am creating a traffic simulator, I have my vehicle and traffic light system working. My vehicle stops when the traffic light is red but it stops wherever it is when the light turns red. I tried specifying the range too. I heard about this unity feature called OnTriggerEnter/Exit/Stay, can someone please tell me if this will work in the traffic lights context? I am implementing my project on unity3d and using C# for coding. Here's a part of my code: material1 is the red traffic light. range = minimum specified distance between vehicle current position and traffic light location.
if(!(m.CM.color.Equals(material1.color)) && (Vector3.Distance(
transform.position, TrafficLightPosition <= range) )) {
ApplySteer ();
Drive (1);
CheckWaypointDistance ();
LerpToSteerAngle ();
}
Answer by Paricus · May 26, 2017 at 07:30 PM
yeah, I'd use OnTriggerStay and run your if statement there (it gets called every frame for objects with triggers). Forget about the range because the trigger will essentially handle that.
void OnTriggerStay ()
{
if(!(m.CM.color.Equals(material1.color))
//do your thing
}
Good Luck!
Your answer
![](https://koobas.hobune.stream/wayback/20220612122836im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Roads and traffics system Made my system extremely slow 0 Answers
Simplified vehicle physics for ambient traffic vehicles 1 Answer
Pathfinding with Roads 2 Answers
How can I make simple traffic lights? 0 Answers
Cars should stop at traffic lights 1 Answer