Files
2026-10-21 05:19:30 +08:00

119 lines
3.3 KiB
C#

using System.Collections.Generic;
using UnityEngine;
// 彈道線 : 每發子彈從槍的位置拉一條線到命中點,很快淡出,只是提示打到哪裡
// 掛在 Main Camera 上 (或任何物件),接上 WeaponLoadout 即可
public class BulletTracer : MonoBehaviour
{
[Header("參照")]
public WeaponLoadout loadout;
[Tooltip("Main Camera,線的起點是相對於它的位置")]
public Camera aimCamera;
[Header("外觀")]
[Tooltip("起點 (相對於相機) : 往右、往下、往前,大約是槍的位置")]
public Vector3 startOffset = new Vector3(0.25f, -0.15f, 0.5f);
public float width = 0.01f;
public Color color = new Color(1f, 0.9f, 0.6f, 0.8f);
[Tooltip("線停留的時間 (秒)")]
public float lifetime = 0.06f;
[Tooltip("線用的材質,不填會自動用不受光照影響的預設材質")]
public Material lineMaterial;
private class Tracer
{
public LineRenderer line;
public float timeLeft;
}
private readonly List<Tracer> tracers = new List<Tracer>();
private HitscanWeapon subscribed;
void Awake()
{
if (lineMaterial == null)
{
lineMaterial = new Material(Shader.Find("Sprites/Default"));
}
}
void OnDisable()
{
Subscribe(null);
}
void Update()
{
// 切槍時改聽新的那一把
HitscanWeapon current = loadout != null ? loadout.Current : null;
if (current != subscribed) Subscribe(current);
// 淡出並回收
foreach (Tracer t in tracers)
{
if (t.timeLeft <= 0f) continue;
t.timeLeft -= Time.deltaTime;
if (t.timeLeft <= 0f)
{
t.line.enabled = false;
continue;
}
Color c = color;
c.a *= t.timeLeft / lifetime;
t.line.startColor = c;
t.line.endColor = c;
}
}
void Subscribe(HitscanWeapon weapon)
{
if (subscribed != null) subscribed.ShotTraced -= OnShotTraced;
subscribed = weapon;
if (subscribed != null) subscribed.ShotTraced += OnShotTraced;
}
void OnShotTraced(Vector3 end)
{
if (aimCamera == null) return;
Tracer t = GetFreeTracer();
t.line.SetPosition(0, aimCamera.transform.TransformPoint(startOffset));
t.line.SetPosition(1, end);
t.line.startColor = color;
t.line.endColor = color;
t.line.enabled = true;
t.timeLeft = lifetime;
}
// 重複使用已經淡出的線,不夠才新增 (Uzi 連射時同時會有好幾條)
Tracer GetFreeTracer()
{
foreach (Tracer t in tracers)
{
if (t.timeLeft <= 0f) return t;
}
GameObject go = new GameObject("Tracer");
go.transform.SetParent(transform, false);
LineRenderer line = go.AddComponent<LineRenderer>();
line.useWorldSpace = true;
line.positionCount = 2;
line.startWidth = width;
line.endWidth = width;
line.material = lineMaterial;
line.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
line.receiveShadows = false;
Tracer created = new Tracer { line = line };
tracers.Add(created);
return created;
}
}