Files
CartoonCopChase/Assets/Scripts/UIController.cs

110 lines
3.2 KiB
C#
Raw Permalink Normal View History

2026-08-28 16:09:06 +01:00
using UnityEngine;
using TMPro; // TextMeshPro for UI
using ArcadeVP;
public class UIController : MonoBehaviour
{
[Header("Player References")]
[Tooltip("Leave empty to auto-find the player via tag")]
public ArcadeVehicleController playerCar;
public CarHealth playerHealth;
[Header("UI Text Elements")]
public TextMeshProUGUI speedText;
public TextMeshProUGUI healthText;
public TextMeshProUGUI pursuerCountText;
private AIController[] allAI;
void Start()
{
// Auto-find player if not assigned in the inspector
if (playerCar == null)
{
ArcadeVehicleController[] cars = FindObjectsByType<ArcadeVehicleController>(FindObjectsSortMode.None);
foreach (var car in cars)
{
if (car.CompareTag("Player"))
{
playerCar = car;
break;
}
}
}
// Auto-find health component on the player
if (playerHealth == null && playerCar != null)
{
playerHealth = playerCar.GetComponent<CarHealth>();
}
// Find all police AI cars in the scene
allAI = FindObjectsByType<AIController>(FindObjectsSortMode.None);
}
void Update()
{
UpdateSpeedUI();
UpdateHealthUI();
UpdatePursuerUI();
}
private void UpdateSpeedUI()
{
if (speedText != null && playerCar != null && playerCar.carBody != null)
{
// Unity physics velocity is in meters per second (m/s).
// Multiply by 3.6 to get KM/H (or by 2.237 to get MPH).
float speedKmh = playerCar.carBody.linearVelocity.magnitude * 3.6f;
speedText.text = $"{Mathf.RoundToInt(speedKmh)} KM/H";
}
}
private void UpdateHealthUI()
{
if (healthText != null && playerHealth != null)
{
// Update the health text (e.g., "Health: 85")
int roundedHealth = Mathf.Max(0, Mathf.RoundToInt(playerHealth.currentHealth));
healthText.text = $"Health: {roundedHealth}";
// Optional: Color code the health
if (playerHealth.currentHealth > 50)
healthText.color = Color.green;
else if (playerHealth.currentHealth > 20)
healthText.color = new Color(1f, 0.5f, 0f); // Orange
else
healthText.color = Color.red;
}
}
private void UpdatePursuerUI()
{
if (pursuerCountText != null && allAI != null)
{
int activePursuers = 0;
// Loop through all AI cars and check their actual state
foreach (AIController ai in allAI)
{
if (ai != null && ai.currentState == AIController.AIState.Pursue)
{
activePursuers++;
}
}
if (activePursuers > 0)
{
pursuerCountText.text = $"WANTED: {activePursuers} COP(S) CHASING";
pursuerCountText.color = Color.red;
}
else
{
pursuerCountText.text = "STATUS: HIDDEN";
pursuerCountText.color = Color.gray;
}
}
}
}