using UnityEngine; using UnityEngine.UI; public abstract class WeaponBase : MonoBehaviour { [Header("Weapon Settings")] public GameObject bulletPrefab; public Transform gunTip; public Camera playerCamera; public float bulletSpeed = 50f; public float fireRate = 0.2f; public int reserveAmmo = 30; public AudioClip shootSound; public Text ammoText; [Header("Crosshair Settings")] public Sprite crosshairSprite; // 🔥 Custom crosshair for each weapon public Image crosshairUI; // 🔥 UI crosshair image protected float lastFireTime = 0f; protected virtual void Start() { // 🔥 Change crosshair when this weapon is equipped if (crosshairUI != null && crosshairSprite != null) { crosshairUI.sprite = crosshairSprite; } } protected virtual void Update() { if (gameObject.activeInHierarchy && CanFire()) { Fire(); } } protected virtual bool CanFire() { return false; // Will be overridden in child classes } protected virtual void Fire() { lastFireTime = Time.time; if (reserveAmmo <= 0) return; if (shootSound != null) { AudioSource.PlayClipAtPoint(shootSound, gunTip.position); } // 🔥 Aim directly at the crosshair (center of the screen) Vector3 screenCenter = new Vector3(Screen.width / 2, Screen.height / 2, 0); Ray ray = playerCamera.ScreenPointToRay(screenCenter); RaycastHit hit; Vector3 targetPoint; if (Physics.Raycast(ray, out hit, 100f)) // 🔥 Check if we hit something { targetPoint = hit.point; } else { targetPoint = ray.GetPoint(100f); // 🔥 Shoot straight ahead } // 🔥 Fire the bullet towards the target point Vector3 direction = (targetPoint - gunTip.position).normalized; GameObject bullet = Instantiate(bulletPrefab, gunTip.position, Quaternion.LookRotation(direction)); bullet.GetComponent<Rigidbody>().velocity = direction * bulletSpeed; Destroy(bullet, 2f); reserveAmmo--; UpdateAmmoUI(); } public virtual void UpdateAmmoUI() { if (ammoText != null) ammoText.text = $"Ammo: {reserveAmmo}"; } }