230 lines
7.6 KiB
C#
230 lines
7.6 KiB
C#
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 float ReloadRemaining => IsReloading ? Mathf.Max(0f, reloadEndTime - Time.time) : 0f; // 換彈剩餘秒數
|
|
public int RecoilSeed { get; private set; } // 後座力隨機部分的種子,記錄下來就能重現
|
|
|
|
public event Action Fired;
|
|
public event Action<BodyPart, float> HitLanded; // 部位、實際傷害
|
|
public event Action<Vector3> ShotTraced; // 每顆子彈 (彈丸) 停下的位置,給彈道線用
|
|
|
|
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;
|
|
Vector3 end = origin + direction * data.range; // 什麼都沒打到就畫到射程盡頭
|
|
|
|
RaycastHit? stop = FindFirstHit(origin, direction);
|
|
if (stop.HasValue)
|
|
{
|
|
end = stop.Value.point;
|
|
|
|
if (stop.Value.collider.TryGetComponent(out Hitbox hitbox))
|
|
{
|
|
float dealt = hitbox.Hit(data.damage);
|
|
if (dealt > 0f) HitLanded?.Invoke(hitbox.part, dealt);
|
|
}
|
|
}
|
|
|
|
ShotTraced?.Invoke(end);
|
|
}
|
|
|
|
// 依距離由近到遠檢查 : 自己 → 略過 ; 命中框 → 命中 ; 機器人的移動膠囊 → 略過 ; 其他 (牆) → 擋住
|
|
RaycastHit? FindFirstHit(Vector3 origin, Vector3 direction)
|
|
{
|
|
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 _)) return hitBuffer[i];
|
|
if (col.isTrigger || col.GetComponentInParent<BotHealth>() != null) continue;
|
|
|
|
return hitBuffer[i]; // 被牆或其他東西擋住
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
void StartReload()
|
|
{
|
|
if (IsReloading || Ammo >= data.magazineSize) return;
|
|
|
|
float duration = Ammo == 0 && data.emptyReloadTime > 0f ? data.emptyReloadTime : data.reloadTime;
|
|
reloadEndTime = Time.time + duration;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|