Advertisement
gandalfbialy

Untitled

Jul 19th, 2025
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.01 KB | None | 0 0
  1. // RaceController.cs
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. using TMPro;
  5. using Photon.Pun;
  6. using Photon.Realtime;
  7.  
  8. public class RaceController : MonoBehaviourPunCallbacks
  9. {
  10.     [Header("Race Settings")]
  11.     public int countdownStart = 3;
  12.     public static int totalLaps = 2;
  13.     public static bool isRacing = false;
  14.  
  15.     [Header("UI Elements")]
  16.     public GameObject endRacePanel;
  17.     public TMP_Text startText;
  18.     public Button startButton;
  19.     public GameObject waitingText;
  20.  
  21.     [Header("Car Prefab & Spawns")]
  22.     public GameObject carPrefab;      // musi leżeć w Resources/
  23.     public Transform[] spawnPositions;
  24.  
  25.     [Header("Audio Clips")]
  26.     public AudioClip countSound;
  27.     public AudioClip startSound;
  28.  
  29.     private AudioSource audioSource;
  30.     private int timer;
  31.     private CheckpointController[] carsControllers;
  32.  
  33.     void Awake()
  34.     {
  35.         // Wstępna konfiguracja UI i audio
  36.         audioSource = GetComponent<AudioSource>();
  37.         endRacePanel.SetActive(false);
  38.         startText.gameObject.SetActive(false);
  39.         startButton.gameObject.SetActive(false);
  40.         waitingText.SetActive(false);
  41.  
  42.         // Synchronizuj scenę automatycznie przez Photona
  43.         PhotonNetwork.AutomaticallySyncScene = true;
  44.  
  45.         if (PhotonNetwork.InRoom)
  46.         {
  47.             SpawnLocalCar();
  48.             SetupStartUI();
  49.         }
  50.     }
  51.  
  52.     void Start()
  53.     {
  54.         timer = countdownStart;
  55.  
  56.         // Jeśli klient jest już w pokoju (np. szybkie dołączenie),
  57.         // od razu spawn i konfiguruj UI
  58.         //if (PhotonNetwork.InRoom)
  59.         //{
  60.         //    SpawnLocalCar();
  61.         //    SetupStartUI();
  62.         //}
  63.     }
  64.  
  65.     public override void OnJoinedRoom()
  66.     {
  67.         base.OnJoinedRoom();
  68.         // Gdy callback potwierdzi dołączenie: stwórz auto i przygotuj UI
  69.         SpawnLocalCar();
  70.         SetupStartUI();
  71.     }
  72.  
  73.     public override void OnMasterClientSwitched(Player newMasterClient)
  74.     {
  75.         base.OnMasterClientSwitched(newMasterClient);
  76.  
  77.         // Jeśli to MY zostałem nowym hostem, przypnij kamerę do mojego auta
  78.         if (PhotonNetwork.IsMasterClient)
  79.         {
  80.             var camCtrl = FindFirstObjectByType<CameraController>();
  81.             if (camCtrl != null)
  82.             {
  83.                 // Znajdź moje auto i przypnij do niego kamerę
  84.                 var myCar = FindMyLocalCar();
  85.                 if (myCar != null)
  86.                 {
  87.                     camCtrl.SetCameraProperties(myCar);
  88.                 }
  89.             }
  90.         }
  91.     }
  92.  
  93.     /// <summary>
  94.     /// Znajduje auto lokalnego gracza (które należy do tego klienta)
  95.     /// </summary>
  96.     private GameObject FindMyLocalCar()
  97.     {
  98.         var cars = GameObject.FindGameObjectsWithTag("Car");
  99.         foreach (var car in cars)
  100.         {
  101.             var photonView = car.GetComponent<PhotonView>();
  102.             if (photonView != null && photonView.IsMine)
  103.             {
  104.                 return car;
  105.             }
  106.         }
  107.         return null;
  108.     }
  109.  
  110.     /// <summary>
  111.     /// Wyświetla MasterClientowi przycisk Start, innym – komunikat "Czekaj na start".
  112.     /// </summary>
  113.     private void SetupStartUI()
  114.     {
  115.         if (PhotonNetwork.IsMasterClient)
  116.         {
  117.             startButton.gameObject.SetActive(true);
  118.             startButton.onClick.AddListener(BeginGame);
  119.         }
  120.         else
  121.         {
  122.             waitingText.SetActive(true);
  123.         }
  124.     }
  125.  
  126.     /// <summary>
  127.     /// Wywoływane przez MasterClienta – RPC do wszystkich o starcie wyścigu.
  128.     /// </summary>
  129.     public void BeginGame()
  130.     {
  131.         photonView.RPC(nameof(StartGame), RpcTarget.All);
  132.     }
  133.  
  134.     [PunRPC]
  135.     private void StartGame()
  136.     {
  137.         // Schowaj UI startowe
  138.         waitingText.SetActive(false);
  139.         startButton.gameObject.SetActive(false);
  140.  
  141.         // Rozpocznij odliczanie
  142.         InvokeRepeating(nameof(CountDown), 1f, 1f);
  143.     }
  144.  
  145.     private void CountDown()
  146.     {
  147.         startText.gameObject.SetActive(true);
  148.  
  149.         if (timer > 0)
  150.         {
  151.             startText.text = timer.ToString();
  152.             audioSource.PlayOneShot(countSound);
  153.             timer--;
  154.         }
  155.         else
  156.         {
  157.             startText.text = "START!";
  158.             audioSource.PlayOneShot(startSound);
  159.  
  160.             isRacing = true;
  161.             CancelInvoke(nameof(CountDown));
  162.             Invoke(nameof(HideStartText), 1f);
  163.  
  164.             // Po starcie zbierz wszystkie CheckpointController’y
  165.             SetupCheckpointControllers();
  166.         }
  167.     }
  168.  
  169.     private void HideStartText()
  170.     {
  171.         startText.gameObject.SetActive(false);
  172.     }
  173.  
  174.     /// <summary>
  175.     /// Tworzy samochód lokalnego gracza dopiero po wejściu do pokoju.
  176.     /// </summary>
  177.     private GameObject SpawnLocalCar()
  178.     {
  179.         // ActorNumber zaczyna się od 1, więc idx = ActorNumber-1
  180.         int idx = PhotonNetwork.LocalPlayer.ActorNumber - 1;
  181.         Vector3 pos = spawnPositions[idx].position;
  182.         Quaternion rot = spawnPositions[idx].rotation;
  183.  
  184.         // Dane do CarAppearance lub OnlinePlayer
  185.         object[] instData = new object[]
  186.         {
  187.             PlayerPrefs.GetString("PlayerName"),
  188.             PlayerPrefs.GetInt("Red"),
  189.             PlayerPrefs.GetInt("Green"),
  190.             PlayerPrefs.GetInt("Blue")
  191.         };
  192.  
  193.         // Instantiate z Photonem – wysyła do wszystkich event
  194.         GameObject car = PhotonNetwork.Instantiate(
  195.             carPrefab.name,
  196.             pos, rot,
  197.             0,
  198.             instData
  199.         );
  200.  
  201.         // Włącz lokalne sterowanie
  202.         car.GetComponent<DrivingScript>().enabled = true;
  203.         car.GetComponent<PlayerController>().enabled = true;
  204.  
  205.         // Kamera podąża tylko za hostem (MasterClient)
  206.         if (PhotonNetwork.IsMasterClient)
  207.         {
  208.             var camCtrl = FindFirstObjectByType<CameraController>();
  209.             if (camCtrl != null)
  210.             {
  211.                 camCtrl.SetCameraProperties(car);
  212.             }
  213.         }
  214.  
  215.         return car;
  216.     }
  217.  
  218.     /// <summary>
  219.     /// Zbiera wszystkie CheckpointController’y z tagiem "Car" do sprawdzania mety.
  220.     /// </summary>
  221.     private void SetupCheckpointControllers()
  222.     {
  223.         var cars = GameObject.FindGameObjectsWithTag("Car");
  224.         carsControllers = new CheckpointController[cars.Length];
  225.         for (int i = 0; i < cars.Length; i++)
  226.         {
  227.             carsControllers[i] = cars[i].GetComponent<CheckpointController>();
  228.         }
  229.     }
  230.  
  231.     void LateUpdate()
  232.     {
  233.         // Jeśli wyścig trwa i mamy kontrolery – sprawdzamy, czy wszyscy ukończyli
  234.         if (!isRacing || carsControllers == null) return;
  235.  
  236.         int finished = 0;
  237.         foreach (var ctrl in carsControllers)
  238.         {
  239.             if (ctrl.lap > totalLaps)
  240.                 finished++;
  241.         }
  242.  
  243.         if (finished == carsControllers.Length)
  244.         {
  245.             isRacing = false;
  246.             endRacePanel.SetActive(true);
  247.             Debug.Log("Wyścig skończony");
  248.         }
  249.     }
  250. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement