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

+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f58858b2fc0701f449d37658ff31934c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+130
View File
@@ -0,0 +1,130 @@
using System;
using UnityEngine;
using CharacterMovement;
// 機器人的 AI : 代替鍵盤餵輸入給 MotionCore 的 PlayerController,物理和玩家完全一樣
// 行為 : 面向玩家,隨機左右橫移,偶爾停頓、跳躍、滑鏟
[RequireComponent(typeof(PlayerController))]
public class BotBrain : MonoBehaviour, ICharacterInputSource
{
[Header("目標 (由 BotSpawner 設定)")]
public Transform target;
[Header("活動範圍 (由 BotSpawner 設定)")]
public Vector3 areaCenter;
public float areaRadius = 15f;
[Header("橫移")]
[Tooltip("每段橫移的持續時間範圍 (秒)")]
public Vector2 strafeDuration = new Vector2(0.3f, 1.2f);
[Tooltip("每段結束時改成停頓的機率")]
[Range(0f, 1f)] public float pauseChance = 0.15f;
[Header("跳躍 / 滑鏟 (每段開始時判定一次)")]
[Range(0f, 1f)] public float jumpChance = 0.15f;
[Range(0f, 1f)] public float slideChance = 0.1f;
[Tooltip("滑鏟時按住蹲下的時間 (秒)")]
public float slideHoldTime = 0.6f;
private PlayerController player;
private Rigidbody body;
private float segmentTimer;
private float jumpHeldTimer;
private float slideTimer;
// ===== ICharacterInputSource : MotionCore 每幀讀這些值 =====
public Vector2 MoveDirection { get; private set; }
public bool IsMoving => MoveDirection.sqrMagnitude > 0.0001f;
public bool IsSprinting => slideTimer > 0f; // 滑鏟要在衝刺中才能觸發
public bool IsWalking => false;
public bool IsCrouching => slideTimer > 0f;
public bool IsProne => false;
public bool IsJumpHeld => jumpHeldTimer > 0f;
public event Action JumpPerformed;
public event Action CrouchPerformed;
#pragma warning disable 0067 // 介面要求,但機器人不會衝刺技能和趴下
public event Action DashPerformed;
public event Action PronePerformed;
#pragma warning restore 0067
// ==========================================================
void Awake()
{
player = GetComponent<PlayerController>();
body = GetComponent<Rigidbody>();
// 朝向由這裡控制 (面向玩家),不讓 MotionCore 把身體轉向移動方向
player.SetMovementFacingEnabled(false);
}
void Update()
{
// PlayerController 在自己的 Start 才設定輸入來源,所以等到 Update 才換成自己
if (!ReferenceEquals(player.InputSource, this))
{
player.SetInputSource(this);
}
float dt = Time.deltaTime;
if (jumpHeldTimer > 0f) jumpHeldTimer -= dt;
if (slideTimer > 0f) slideTimer -= dt;
segmentTimer -= dt;
if (segmentTimer <= 0f)
{
StartNewSegment();
}
}
void FixedUpdate()
{
// 只轉水平方向面向玩家,移動方向是相對於自己的朝向,所以左右就是對玩家橫移
if (target == null || body == null) return;
Vector3 toTarget = Vector3.ProjectOnPlane(target.position - body.position, Vector3.up);
if (toTarget.sqrMagnitude > 0.01f)
{
body.MoveRotation(Quaternion.LookRotation(toTarget.normalized, Vector3.up));
}
}
void StartNewSegment()
{
segmentTimer = UnityEngine.Random.Range(strafeDuration.x, strafeDuration.y);
if (UnityEngine.Random.value < pauseChance)
{
MoveDirection = Vector2.zero;
return;
}
MoveDirection = PickMoveDirection();
if (UnityEngine.Random.value < jumpChance)
{
jumpHeldTimer = 0.25f; // 按住一下才會跳到完整高度
JumpPerformed?.Invoke();
}
else if (UnityEngine.Random.value < slideChance)
{
slideTimer = slideHoldTime; // 先讓 IsSprinting / IsCrouching 成立,再送出蹲下
CrouchPerformed?.Invoke();
}
}
// 平常隨機往左或往右 ; 跑出活動範圍時直接往中心走 (用自己朝向的座標表示)
Vector2 PickMoveDirection()
{
Vector3 toCenter = Vector3.ProjectOnPlane(areaCenter - transform.position, Vector3.up);
if (toCenter.magnitude > areaRadius)
{
Vector3 local = transform.InverseTransformDirection(toCenter.normalized);
return new Vector2(local.x, local.z).normalized;
}
return new Vector2(UnityEngine.Random.value < 0.5f ? -1f : 1f, 0f);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bfef044fbd098624a8fcf6725e922a34
+64
View File
@@ -0,0 +1,64 @@
using System;
using UnityEngine;
using CharacterMovement;
// 機器人的血量 : 掛在機器人根物件上
public class BotHealth : MonoBehaviour
{
[Header("血量")]
public float maxHealth = 500f;
[Header("死亡")]
[Tooltip("機器人模型上的 Animator,死亡時觸發 Die")]
public Animator animator;
[Tooltip("倒下後多久移除 (秒)")]
public float destroyDelay = 3f;
public float Health { get; private set; }
public bool IsDead { get; private set; }
// 給 BotSpawner 用 : 倒下時通知,準備重生下一隻
public event Action<BotHealth> Died;
void Awake()
{
Health = maxHealth;
}
public void TakeDamage(float amount, BodyPart part)
{
if (IsDead) return;
Health = Mathf.Max(0f, Health - amount);
if (Health <= 0f)
{
Die();
}
}
void Die()
{
IsDead = true;
// 停止移動與 AI
if (TryGetComponent(out BotBrain brain)) brain.enabled = false;
if (TryGetComponent(out PlayerController controller)) controller.enabled = false;
if (TryGetComponent(out Rigidbody body))
{
body.linearVelocity = Vector3.zero;
body.isKinematic = true;
}
// 關掉命中框,倒下的機器人不會擋子彈
foreach (Hitbox hitbox in GetComponentsInChildren<Hitbox>())
{
if (hitbox.TryGetComponent(out Collider col)) col.enabled = false;
}
if (animator != null) animator.SetTrigger("Die");
Died?.Invoke(this);
Destroy(gameObject, destroyDelay);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 451ce8b34d8695641b90837ce06f78d1
+83
View File
@@ -0,0 +1,83 @@
using System.Collections;
using UnityEngine;
// 一次只有一隻機器人,倒下後在隨機位置重生下一隻
// 掛在場景裡的空物件上,物件的位置就是生成範圍的中心
public class BotSpawner : MonoBehaviour
{
[Header("參照")]
[Tooltip("機器人 prefab (要有 BotBrain、BotHealth)")]
public BotBrain botPrefab;
[Tooltip("玩家 (機器人會面向它)")]
public Transform player;
[Header("生成範圍")]
[Tooltip("以這個物件為中心的半徑 (m),要比場地小,避免生成在牆裡")]
public float spawnRadius = 15f;
[Tooltip("離玩家的最小距離 (m)")]
public float minDistanceFromPlayer = 8f;
[Header("重生")]
[Tooltip("倒下後多久生成下一隻 (秒)")]
public float respawnDelay = 1.5f;
void Start()
{
Spawn();
}
void Spawn()
{
if (botPrefab == null) return;
BotBrain bot = Instantiate(botPrefab, PickSpawnPoint(), Quaternion.identity);
bot.target = player;
bot.areaCenter = transform.position;
bot.areaRadius = spawnRadius;
if (bot.TryGetComponent(out BotHealth health))
{
health.Died += OnBotDied;
}
}
void OnBotDied(BotHealth bot)
{
bot.Died -= OnBotDied;
StartCoroutine(RespawnAfterDelay());
}
IEnumerator RespawnAfterDelay()
{
yield return new WaitForSeconds(respawnDelay);
Spawn();
}
// 在範圍內隨機選點,盡量離玩家遠一點 ; 試幾次都太近就用最後一次的結果
Vector3 PickSpawnPoint()
{
Vector3 point = transform.position;
for (int i = 0; i < 20; i++)
{
Vector2 offset = Random.insideUnitCircle * spawnRadius;
point = transform.position + new Vector3(offset.x, 0f, offset.y);
if (player == null || Vector3.Distance(point, player.position) >= minDistanceFromPlayer)
{
break;
}
}
return point;
}
// 在 Scene 視窗畫出生成範圍,方便調整
void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, spawnRadius);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ffa4aa80237c6424cbefd7a1db794702
+43
View File
@@ -0,0 +1,43 @@
using UnityEngine;
public enum BodyPart
{
Head,
Body,
Leg
}
// 掛在機器人骨頭上的命中框 (Collider 要勾 Is Trigger)
public class Hitbox : MonoBehaviour
{
[Header("部位")]
public BodyPart part = BodyPart.Body;
private BotHealth owner;
void Awake()
{
owner = GetComponentInParent<BotHealth>();
}
// 部位傷害倍率 : 頭 ×1.5、身體 ×1、腿 ×0.7
public static float GetMultiplier(BodyPart part)
{
switch (part)
{
case BodyPart.Head: return 1.5f;
case BodyPart.Leg: return 0.7f;
default: return 1f;
}
}
// 回傳實際造成的傷害 (機器人已經倒下就回傳 0)
public float Hit(float baseDamage)
{
if (owner == null || owner.IsDead) return 0f;
float damage = baseDamage * GetMultiplier(part);
owner.TakeDamage(damage, part);
return damage;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a53cad675bcc11640ae35481c28700e7
+33 -1
View File
@@ -47,6 +47,24 @@ public class PlayerLook : MonoBehaviour
pendingAssistDelta += delta;
}
// ===== 後座力 =====
// 後座力是疊在滑鼠視角上的一層獨立偏移 (度),不會改到 yaw / pitch,停火後自己回正
// x = 往右,y = 往上 ; 記錄器之後可以把它和滑鼠輸入分開存
public Vector2 RecoilOffset { get; private set; }
private float recoilRecoverDelay;
private float recoilRecoverSpeed;
private float timeSinceRecoil;
// recoverDelay : 最後一發後多久開始回正 (秒) ; recoverSpeed : 回正速度 (度/秒)
public void AddRecoil(Vector2 kick, float recoverDelay, float recoverSpeed)
{
RecoilOffset += kick;
recoilRecoverDelay = recoverDelay;
recoilRecoverSpeed = recoverSpeed;
timeSinceRecoil = 0f;
}
// =============================
void Start()
@@ -77,7 +95,11 @@ public class PlayerLook : MonoBehaviour
pitch -= totalDelta.y * degreesPerCount; // 滑鼠往上 = 抬頭
pitch = Mathf.Clamp(pitch, -maxPitch, maxPitch);
transform.rotation = Quaternion.Euler(pitch, yaw, 0f);
UpdateRecoilRecovery();
// 最終視角 = 滑鼠 (含輔助) 的角度 + 後座力偏移
float viewPitch = Mathf.Clamp(pitch - RecoilOffset.y, -maxPitch, maxPitch);
transform.rotation = Quaternion.Euler(viewPitch, yaw + RecoilOffset.x, 0f);
UpdateEyeHeight();
@@ -88,6 +110,16 @@ public class PlayerLook : MonoBehaviour
}
}
void UpdateRecoilRecovery()
{
if (RecoilOffset == Vector2.zero) return;
timeSinceRecoil += Time.deltaTime;
if (timeSinceRecoil < recoilRecoverDelay) return;
RecoilOffset = Vector2.MoveTowards(RecoilOffset, Vector2.zero, recoilRecoverSpeed * Time.deltaTime);
}
void UpdateEyeHeight()
{
if (bodyCapsule == null) return;
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5e3a5f1477677c14eb5284511f5e2a67
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -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