This commit is contained in:
Sahik committed 2026-10-20 15:21:09 +08:00
1 parent 18f513af38
commit ac91ce5ca7
36 files changed
+2114 -25

No files matched your search

@@ -0,0 +1,211 @@
using System;
using UnityEngine;
using UnityEngine.InputSystem;
// 掛在每把槍的模型物件上 (Main Camera 底下),一把槍一個,由 WeaponLoadout 決定啟用哪一把
// 負責 : 開火、命中判定、彈匣與換彈、後座力、槍模型往後彈的畫面效果
public class HitscanWeapon : MonoBehaviour
{
[Header("數值")]
public WeaponData data;
[Header("參照")]
[Tooltip("Main Camera,子彈從畫面中心射出")]
public Camera aimCamera;
[Tooltip("CameraRoot 上的 PlayerLook,後座力加在這裡")]
public PlayerLook playerLook;
[Tooltip("Player 根物件,射擊時略過自己的碰撞體")]
public Transform playerRoot;
[Header("槍口火光 (可不填)")]
public GameObject muzzleFlashPrefab;
public Transform muzzlePoint;
// 給 HUD / 之後的記錄器用
public int Ammo { get; private set; }
public bool IsReloading => reloadEndTime > 0f;
public int RecoilSeed { get; private set; } // 後座力隨機部分的種子,記錄下來就能重現
public event Action Fired;
public event Action<BodyPart, float> HitLanded; // 部位、實際傷害
private float nextFireTime;
private float lastShotTime = -999f;
private float reloadEndTime;
private int sprayIndex; // 這次連射的第幾發 (1 開始)
private System.Random recoilRandom;
private Vector3 restLocalPosition;
private readonly RaycastHit[] hitBuffer = new RaycastHit[32];
void Awake()
{
restLocalPosition = transform.localPosition;
Ammo = data != null ? data.magazineSize : 0;
RecoilSeed = Environment.TickCount;
recoilRandom = new System.Random(RecoilSeed);
}
void OnDisable()
{
// 切槍時取消換彈,模型回到原位
reloadEndTime = 0f;
transform.localPosition = restLocalPosition;
}
void Update()
{
if (data == null) return;
UpdateReload();
UpdateModelKick();
// 選單開著 (滑鼠沒鎖定) 時不能開槍
if (Cursor.lockState != CursorLockMode.Locked || Mouse.current == null) return;
if (Keyboard.current != null && Keyboard.current.rKey.wasPressedThisFrame)
{
StartReload();
}
bool trigger = data.fullAuto
? Mouse.current.leftButton.isPressed
: Mouse.current.leftButton.wasPressedThisFrame;
if (trigger && !IsReloading && Time.time >= nextFireTime)
{
if (Ammo > 0)
{
Fire();
}
else
{
StartReload(); // 沒子彈時扣板機自動換彈
}
}
}
void Fire()
{
Ammo--;
// 連射時從上一發的時間往後排,不受幀率影響 (否則低幀率時 Uzi 會射得比設定慢)
nextFireTime = Time.time - nextFireTime < data.fireInterval
? nextFireTime + data.fireInterval
: Time.time + data.fireInterval;
// 隔太久沒開槍就算新的一次連射,後座力圖案從頭開始
if (Time.time - lastShotTime > data.fireInterval + data.recoverDelay)
{
sprayIndex = 0;
}
sprayIndex++;
lastShotTime = Time.time;
// 先射擊再加後座力 : 這一發打在準心上,後座力影響的是下一發
for (int i = 0; i < Mathf.Max(1, data.pellets); i++)
{
ShootRay(GetPelletDirection(i));
}
if (playerLook != null)
{
playerLook.AddRecoil(GetRecoilKick(sprayIndex), data.recoverDelay, data.recoverSpeed);
}
transform.localPosition = restLocalPosition - Vector3.forward * data.modelKickBack;
if (muzzleFlashPrefab != null && muzzlePoint != null)
{
Destroy(Instantiate(muzzleFlashPrefab, muzzlePoint.position, muzzlePoint.rotation, muzzlePoint), 0.05f);
}
Fired?.Invoke();
}
// 霰彈的固定圖案 : 第 0 顆在正中間,其餘平均排在散布半徑的圓上
Vector3 GetPelletDirection(int index)
{
Transform cam = aimCamera.transform;
if (data.pellets <= 1 || index == 0 || data.pelletSpread <= 0f)
{
return cam.forward;
}
float angle = (index - 1) * 360f / (data.pellets - 1);
Quaternion around = Quaternion.AngleAxis(angle, cam.forward);
Quaternion tilt = Quaternion.AngleAxis(data.pelletSpread, cam.up);
return around * tilt * cam.forward;
}
// 第 n 發的後座力 (度) : x = 往右,y = 往上
Vector2 GetRecoilKick(int n)
{
float vertical = n <= data.verticalFirstShots ? data.verticalFirst : data.verticalAfter;
float horizontal = 0f;
if (n >= data.horizontalRightFrom && n < data.horizontalLeftFrom) horizontal = data.horizontalStep;
else if (n >= data.horizontalLeftFrom && n <= data.horizontalEndAt) horizontal = -data.horizontalStep;
if (data.horizontalRandom > 0f)
{
horizontal += ((float)recoilRandom.NextDouble() * 2f - 1f) * data.horizontalRandom;
}
return new Vector2(horizontal, vertical);
}
// 依距離由近到遠檢查 : 自己 → 略過 ; 命中框 → 命中 ; 機器人的移動膠囊 → 略過 ; 其他 (牆) → 擋住
void ShootRay(Vector3 direction)
{
Vector3 origin = aimCamera.transform.position;
int count = Physics.RaycastNonAlloc(origin, direction, hitBuffer, data.range, ~0, QueryTriggerInteraction.Collide);
Array.Sort(hitBuffer, 0, count, HitDistanceComparer.Instance);
for (int i = 0; i < count; i++)
{
Collider col = hitBuffer[i].collider;
if (playerRoot != null && col.transform.IsChildOf(playerRoot)) continue;
if (col.TryGetComponent(out Hitbox hitbox))
{
float dealt = hitbox.Hit(data.damage);
if (dealt > 0f) HitLanded?.Invoke(hitbox.part, dealt);
return;
}
if (col.isTrigger || col.GetComponentInParent<BotHealth>() != null) continue;
return; // 被牆或其他東西擋住
}
}
void StartReload()
{
if (IsReloading || Ammo >= data.magazineSize) return;
reloadEndTime = Time.time + data.reloadTime;
}
void UpdateReload()
{
if (IsReloading && Time.time >= reloadEndTime)
{
reloadEndTime = 0f;
Ammo = data.magazineSize;
}
}
void UpdateModelKick()
{
transform.localPosition = Vector3.Lerp(transform.localPosition, restLocalPosition, 1f - Mathf.Exp(-20f * Time.deltaTime));
}
private class HitDistanceComparer : System.Collections.Generic.IComparer<RaycastHit>
{
public static readonly HitDistanceComparer Instance = new HitDistanceComparer();
public int Compare(RaycastHit a, RaycastHit b) => a.distance.CompareTo(b.distance);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 86c6b5cad2146e242a41f45e2e6eedfc
+71
View File
@@ -0,0 +1,71 @@
using UnityEngine;
// 一把槍的數值,一把槍一份資產
// 建立方式 : Project 視窗右鍵 → Create → Mouse Trail Collector → Weapon Data
[CreateAssetMenu(menuName = "Mouse Trail Collector/Weapon Data", fileName = "WeaponData")]
public class WeaponData : ScriptableObject
{
[Header("基本")]
[Tooltip("要和 StartUI 存的武器名稱一致 : M1911 / AK74 / Uzi / Benelli_M4")]
public string weaponName = "M1911";
[Tooltip("勾選 = 全自動 (按住連發),不勾 = 半自動 (點一下一發)")]
public bool fullAuto = false;
[Header("傷害")]
[Tooltip("每顆彈丸打身體的傷害,頭 ×1.5、腿 ×0.7")]
public float damage = 50f;
[Tooltip("每發的彈丸數,霰彈槍才會大於 1")]
public int pellets = 1;
[Tooltip("霰彈的散布半徑 (度),彈丸排成固定圖案 : 中間 1 顆,其餘平均排在這個半徑的圓上")]
public float pelletSpread = 0f;
[Tooltip("射程 (m)")]
public float range = 200f;
[Header("射速與彈匣")]
[Tooltip("兩發之間的最短間隔 (秒)")]
public float fireInterval = 0.143f;
public int magazineSize = 12;
[Tooltip("換彈時間 (秒)")]
public float reloadTime = 1.2f;
[Header("後座力 : 垂直 (度/發,往上)")]
[Tooltip("連射的前幾發")]
public int verticalFirstShots = 5;
public float verticalFirst = 0f;
[Tooltip("之後的每一發")]
public float verticalAfter = 0f;
[Header("後座力 : 水平 S 形 (度/發)")]
[Tooltip("每發往左或往右的固定量")]
public float horizontalStep = 0f;
[Tooltip("第幾發開始往右 (含)")]
public int horizontalRightFrom = 6;
[Tooltip("第幾發開始改往左 (含)")]
public int horizontalLeftFrom = 16;
[Tooltip("第幾發之後就不再左右飄")]
public int horizontalEndAt = 25;
[Tooltip("每發額外加上的隨機左右量 (± 度)")]
public float horizontalRandom = 0f;
[Header("後座力 : 回正")]
[Tooltip("最後一發後多久開始回正 (秒)")]
public float recoverDelay = 0.15f;
[Tooltip("回正速度 (度/秒)")]
public float recoverSpeed = 10f;
[Header("畫面效果 (不影響準心)")]
[Tooltip("開槍時槍模型往後退的距離 (m)")]
public float modelKickBack = 0.03f;
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 034e069ed5f7d6d4ba3d9e64bb0f44e8
+84
View File
@@ -0,0 +1,84 @@
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;
[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;
void Start()
{
if (hitMarker != null) hitMarker.enabled = false;
}
void OnDisable()
{
Subscribe(null);
}
void Update()
{
// 切槍時改聽新的那一把
HitscanWeapon current = loadout != null ? loadout.Current : null;
if (current != subscribed) Subscribe(current);
UpdateHitMarker();
UpdateAmmoText(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}";
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f5da41ae4773f7419675bd3ff836b02
@@ -0,0 +1,55 @@
using UnityEngine;
using UnityEngine.InputSystem;
// 依照 StartUI 選的武器,只啟用對應的那一把槍
// 測試模式下可以用 1~4 鍵切換,方便比較手感
public class WeaponLoadout : MonoBehaviour
{
[Header("武器 (順序對應 1~4 鍵)")]
[Tooltip("每把槍模型上的 HitscanWeapon")]
public HitscanWeapon[] weapons;
public HitscanWeapon Current { get; private set; }
private bool allowSwitch;
void Start()
{
GameSettings settings = GameSettings.Load();
allowSwitch = settings.isTest;
int index = 0;
for (int i = 0; i < weapons.Length; i++)
{
if (weapons[i] != null && weapons[i].data != null && weapons[i].data.weaponName == settings.weapon)
{
index = i;
break;
}
}
Equip(index);
}
void Update()
{
if (!allowSwitch || Keyboard.current == null) return;
if (Keyboard.current.digit1Key.wasPressedThisFrame) Equip(0);
else if (Keyboard.current.digit2Key.wasPressedThisFrame) Equip(1);
else if (Keyboard.current.digit3Key.wasPressedThisFrame) Equip(2);
else if (Keyboard.current.digit4Key.wasPressedThisFrame) Equip(3);
}
void Equip(int index)
{
if (index < 0 || index >= weapons.Length || weapons[index] == null) return;
for (int i = 0; i < weapons.Length; i++)
{
if (weapons[i] != null) weapons[i].gameObject.SetActive(i == index);
}
Current = weapons[index];
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c9a11a2deaee4fe498a75ccc7ce89ee7