CarSpawner.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TrafficSimulation{
  5. public class CarSpawner : MonoBehaviour
  6. {
  7. public CarPool carPool;
  8. public TrafficSystem trafficSystem;
  9. public float carSpacing;
  10. public float carSize = 4.0f;
  11. public float bufferZone = 3.0f;
  12. // Start is called before the first frame update
  13. void Start()
  14. {
  15. foreach(Segment segment in trafficSystem.segments){
  16. spawnOnSegment(segment);
  17. }
  18. }
  19. void spawnOnSegment(Segment segment){
  20. if(segment == null){
  21. Debug.Log("Segment is null");
  22. return;
  23. }
  24. if(segment.waypoints.Count <= 2){
  25. Debug.Log("Waypoints not set");
  26. return;
  27. }
  28. float distance = 0.0f;
  29. Waypoint lastWp = null;
  30. foreach(Waypoint wp in segment.waypoints)
  31. {
  32. if(lastWp != null)
  33. {
  34. distance += Vector3.Distance(lastWp.transform.position, wp.transform.position);
  35. float wpDistance = Vector3.Distance(lastWp.transform.position, wp.transform.position);
  36. wpDistance = Mathf.Floor(wpDistance);
  37. float spawnDistance = wpDistance;
  38. spawnDistance -= bufferZone;
  39. while(spawnDistance >= bufferZone)
  40. {
  41. Vector3 spawnPos = lastWp.transform.position;
  42. Quaternion spawnRot = lastWp.transform.rotation;
  43. Vector3 currentRoad = wp.transform.position - lastWp.transform.position;
  44. spawnPos += (currentRoad.normalized * (wpDistance - spawnDistance));
  45. carPool.SpawnCar(spawnPos,spawnRot,wp.transform);
  46. Debug.Log("spawn Car on Segment " + segment.name + " and Waypoint " + lastWp.name + " in Distance " + (wpDistance - spawnDistance));
  47. spawnDistance -= carSize;
  48. spawnDistance -= carSpacing;
  49. }
  50. }
  51. lastWp = wp;
  52. }
  53. Debug.Log("Segment " + segment.name + "distance " + distance );
  54. //Transform spawnPos = segment.waypoints[0].transform;
  55. //spawnPos.LookAt(segment.waypoints[1].transform);
  56. //carPool.spawnCar(spawnPos);
  57. }
  58. }
  59. }