Its not a simple question, you should consider posting this in the community threads instead.
But to get you started, here is how I would do my first prototype:
First I would build the city from elements/nodes and then link these together.
Each part of the road would have its own position, length, roadgrip/de-accelleration on the car tires and perhaps other properties.
Then I would build a circle or an 8 map to see if I could make the cars follow the nodes connected.
Each vehicle only needs to know which node its attached to. When going over the border of a node, it should ask the node what node is connected in that direction. The result is the new connection for the vehicle.
In Update() you let each vehicle move in its own driving direction and do its own “have I reached my goal/waypoint” which is the end of the node.
The thing with this approach is that you can even do it without showing them on the screen, as this can be done in pure CONSOLE programming. We did this at my education in C++ back in 1993, so I know it works.
If you want the cars to have AI enough to avoid driving into each other, then you have to make them aware of each other or perhaps, let the NODE (road part) handle all the attached vehicles.
In our school assignment, we had them all simulated in a que and the assignment was to make them stop for red and drive for green etc. and they couldnt overtake each other, so the slowest vehicles set the pace for the rest.
Again, calling this AI is perhaps a bit too much, but they do move automatically. You could put in some sort of “calculate which route to take” sort of waypoint list and store this inside each car, that way they would have to plan (pathfind) their own routes and you would end up with a map full of vehicles driving around as they please.
If you want this approach, then you could implement a “state machine” in each vehicle too.
Its a simple variable that stores what mode/state your vehicle is in.
It could be:
- calculating route (this could take a while and be split over more than one frame)
- following route
- parked
- holding for red light
- crashed
- run out of gas
- … etc.
inside your Update() you make a switch(vehicleState) and on each case you can call whatever functions you need ot make the vehicle behave like the state its in.
Hope this helps.
The game runs at 60 frames per second, Update() is called 60 times per second, and will do everything inside it within that frame. You can't pause the function in the middle and continue on the next update. If you absolutely have to do that, look up Coroutines on google, which are a bit more complicated, but they are not so bad. Definitely a few steps up from what you are doing here though.
– AlgoUnity