using UnityEngine; using UnityEngine.UI; using TMPro; // 命中提示與彈藥顯示 (準心本身只是畫面正中間的一張 Image,不需要腳本) public class WeaponHUD : MonoBehaviour { [Header("參照")] public WeaponLoadout loadout; [Tooltip("命中提示的 Image (平常隱藏,命中時閃一下)")] public Image hitMarker; [Tooltip("彈藥 Text (TMP),例如「12 / 12」")] public TextMeshProUGUI ammoText; [Tooltip("換彈提示 (換彈中才顯示)")] public GameObject reloadTips; [Tooltip("換彈剩餘時間 Text (TMP),例如「1.4s」,換彈中才顯示")] public TextMeshProUGUI reloadTimeText; [Header("命中提示")] public Color bodyColor = Color.white; public Color headColor = new Color(1f, 0.25f, 0.25f); [Tooltip("顯示時間 (秒)")] public float hitMarkerTime = 0.1f; private HitscanWeapon subscribed; private float hitMarkerTimer; private int shownAmmo = -1; private bool shownReloading; private int shownReloadTenths = -1; // 以 0.1 秒為單位,數字有變才更新文字 void Start() { if (hitMarker != null) hitMarker.enabled = false; if (reloadTips != null) reloadTips.SetActive(false); if (reloadTimeText != null) reloadTimeText.gameObject.SetActive(false); } void OnDisable() { Subscribe(null); } void Update() { // 切槍時改聽新的那一把 HitscanWeapon current = loadout != null ? loadout.Current : null; if (current != subscribed) Subscribe(current); UpdateHitMarker(); UpdateAmmoText(current); UpdateReloadTime(current); } void Subscribe(HitscanWeapon weapon) { if (subscribed != null) subscribed.HitLanded -= OnHitLanded; subscribed = weapon; if (subscribed != null) subscribed.HitLanded += OnHitLanded; shownAmmo = -1; // 強制更新彈藥文字 } void OnHitLanded(BodyPart part, float damage) { if (hitMarker == null) return; hitMarker.color = part == BodyPart.Head ? headColor : bodyColor; hitMarker.enabled = true; hitMarkerTimer = hitMarkerTime; } void UpdateHitMarker() { if (hitMarkerTimer <= 0f) return; hitMarkerTimer -= Time.deltaTime; if (hitMarkerTimer <= 0f && hitMarker != null) hitMarker.enabled = false; } // 數字有變才重設文字,避免每幀重建 TMP void UpdateAmmoText(HitscanWeapon weapon) { if (ammoText == null || weapon == null || weapon.data == null) return; if (weapon.Ammo == shownAmmo && weapon.IsReloading == shownReloading) return; shownAmmo = weapon.Ammo; shownReloading = weapon.IsReloading; ammoText.text = shownReloading ? "換彈中..." : $"{shownAmmo} / {weapon.data.magazineSize}"; if (reloadTips != null) reloadTips.SetActive(shownReloading); if (reloadTimeText != null) reloadTimeText.gameObject.SetActive(shownReloading); } // 換彈剩餘時間,精確到 0.1 秒 (無條件進位,避免還沒換完就顯示 0.0s) void UpdateReloadTime(HitscanWeapon weapon) { if (reloadTimeText == null || weapon == null || !weapon.IsReloading) return; int tenths = Mathf.CeilToInt(weapon.ReloadRemaining * 10f); if (tenths == shownReloadTenths) return; shownReloadTenths = tenths; reloadTimeText.text = $"{tenths / 10f:F1}s"; } }