BITFALL/Assets/Artists/Scripts/Equip/BITGun.cs

521 lines
18 KiB
C#
Raw Normal View History

2023-10-04 16:50:27 +08:00
using System;
2023-08-23 01:59:40 +08:00
using System.Linq;
using BITFALL.Guns.States;
2023-10-31 18:07:15 +08:00
using BITFALL.Player.Equip;
2023-09-01 14:33:54 +08:00
using BITFALL.Player.Movement;
2023-06-08 14:09:50 +08:00
using UnityEngine;
using BITKit;
using BITKit.Entities;
2023-08-27 02:58:19 +08:00
using BITKit.Entities.Melee;
2023-06-08 14:09:50 +08:00
using UnityEngine.InputSystem;
using BITKit.StateMachine;
2023-10-20 19:31:12 +08:00
using Cysharp.Threading.Tasks;
2023-09-01 14:33:54 +08:00
using Unity.Mathematics;
2023-08-27 02:58:19 +08:00
using UnityEngine.InputSystem.Interactions;
2023-08-23 01:59:40 +08:00
#if UNITY_EDITOR
#endif
2023-06-08 14:09:50 +08:00
2023-08-27 02:58:19 +08:00
namespace BITFALL.Guns
2023-06-08 14:09:50 +08:00
{
public interface IGunState : IState { }
2023-08-27 02:58:19 +08:00
2023-06-08 14:09:50 +08:00
[System.Serializable]
public abstract class GunState : IGunState
{
public BITGun root;
2023-10-20 19:31:12 +08:00
[Inject]
protected IEntityMovement _entityMovement;
2023-08-23 01:59:40 +08:00
public bool Enabled { get;set; }
2023-06-08 14:09:50 +08:00
public virtual void Initialize()
{
2023-10-20 19:31:12 +08:00
root.Entity.Inject(this);
2023-08-23 01:59:40 +08:00
_entityMovement.OnStateChanged += OnMovementStateChanged;
2023-06-08 14:09:50 +08:00
}
2023-08-23 01:59:40 +08:00
public virtual void OnStateEntry(IState old)
2023-06-08 14:09:50 +08:00
{
}
public virtual void OnStateExit(IState old, IState newState)
{
}
2023-08-27 02:58:19 +08:00
public virtual void OnStateUpdate(float deltaTime)
2023-06-08 14:09:50 +08:00
{
}
2023-08-23 01:59:40 +08:00
public virtual void OnMovementStateChanged(IEntityMovementState old, IEntityMovementState newState)
{
}
2023-08-27 02:58:19 +08:00
public virtual void AnimationEvent(string name)
{
}
2023-06-08 14:09:50 +08:00
}
[System.Serializable]
public class GunStateMachine : MonoStateMachine<GunState> { }
public class BITGun : BITEquipBase<GunState>
{
2023-08-27 02:58:19 +08:00
//简单设置
[Header(Constant.Header.Settings)]
[SerializeField] private Vector3 bulletInitialOffset;
2023-09-01 14:33:54 +08:00
[SerializeField] private SpringEulerAngle recoilSpring=new();
2023-11-15 23:54:54 +08:00
[SerializeField] private float recoilPositionWeight=1;
2023-11-02 20:58:55 +08:00
[Header(Constant.Header.Gameobjects)]
[SerializeField] private Transform initialSight;
[SerializeField] private Optional<Transform> newSight;
[Header(nameof(Optional<GameObject>))]
[SerializeField] private Optional<LocationAdditive> breathingAdditive;
2023-08-27 02:58:19 +08:00
2023-06-08 14:09:50 +08:00
// 输入系统
[Header(Constant.Header.Input)]
2023-11-02 20:58:55 +08:00
[SerializeField] internal InputActionReference fireAction;
[SerializeField] internal InputActionReference aimAction;
[SerializeField] internal InputActionReference reloadAction;
[SerializeField] internal InputActionReference meleeAction;
[SerializeField] internal InputActionReference steadyAimAction;
2023-10-20 19:31:12 +08:00
[Header(Constant.Header.HotFix)]
[SerializeField] private Transform cameraView;
2023-06-08 14:09:50 +08:00
// 引用组件
[Header(Constant.Header.Components)]
2023-09-01 14:33:54 +08:00
[SerializeField] private LocationAdditive locationAdditive;
2023-11-15 23:54:54 +08:00
[SerializeField] private LocationAdditive selfViewAdditive;
2023-08-27 02:58:19 +08:00
2023-06-08 14:09:50 +08:00
// 引用预制体
[Header(Constant.Header.Prefabs)]
2023-08-23 01:59:40 +08:00
// 内部变量burst
2023-06-08 14:09:50 +08:00
[Header(Constant.Header.InternalVariables)]
2023-08-23 01:59:40 +08:00
public ExpectState<bool> expectFiring;
public ExpectState<bool> expectAiming;
internal readonly IntervalUpdate fireInterval = new(0.32f);
internal readonly IntervalUpdate burstFireInterval = new(0.1f);
2023-06-08 14:09:50 +08:00
internal int burstFireCount;
2023-10-20 19:31:12 +08:00
[Inject]
2023-09-01 14:33:54 +08:00
private IEntityMovement _movement;
2023-10-20 19:31:12 +08:00
[Inject]
2023-09-01 14:33:54 +08:00
private IPlayerMovement _playerMovement;
2023-10-20 19:31:12 +08:00
[Inject]
private IHealth _health;
2023-10-31 18:07:15 +08:00
[Inject] private IEquipService _equipService;
2023-11-21 18:05:18 +08:00
private static readonly int IsGrounded = Animator.StringToHash(BITConstant.Player.IsGrounded);
private static readonly int IsCrouched = Animator.StringToHash(BITConstant.Player.IsCrouched);
2023-10-24 23:37:59 +08:00
private AssetableGun _gun=>item as AssetableGun;
2023-10-20 19:31:12 +08:00
private bool isHolstered;
2023-11-02 20:58:55 +08:00
private bool isSteadyAim;
2023-10-20 19:31:12 +08:00
2023-10-31 18:07:15 +08:00
public bool RequireBolt { get; set; }
2023-06-08 14:09:50 +08:00
#region
2023-10-31 18:07:15 +08:00
public override string AddressablePath => _gun.AddressablePath;
2023-06-08 14:09:50 +08:00
#endregion
2023-11-15 23:54:54 +08:00
2023-08-23 01:59:40 +08:00
public override void OnAwake()
{
base.OnAwake();
2023-10-20 19:31:12 +08:00
inputActionGroup.RegisterCallback(fireAction, OnFire);
inputActionGroup.RegisterCallback(aimAction, OnAim);
inputActionGroup.RegisterCallback(reloadAction, OnReload);
inputActionGroup.RegisterCallback(meleeAction, OnMelee);
2023-11-15 23:54:54 +08:00
if (breathingAdditive.Allow)
inputActionGroup.RegisterCallback(steadyAimAction, OnSteadyAim);
2023-09-01 14:33:54 +08:00
_movement.OnStateChanged += OnMovementStateChanged;
_movement.OnCommand += OnMovementCommand;
2023-11-15 23:54:54 +08:00
animator[0].onStateExit += (state) => { isHolstered = state is BITConstant.Player.Holster; };
2023-10-20 19:31:12 +08:00
2023-11-15 23:54:54 +08:00
BITAppForUnity.AllowCursor.AddListener(OnAllowCursor);
destroyCancellationToken.Register(() =>
2023-10-20 19:31:12 +08:00
{
2023-11-15 23:54:54 +08:00
BITAppForUnity.AllowCursor.RemoveListener(OnAllowCursor);
});
}
private void OnAllowCursor(bool allow)
{
if (!allow) return;
expectFiring.Reset();
expectAiming.Reset();
2023-09-01 14:33:54 +08:00
}
2023-11-02 20:58:55 +08:00
private void OnSteadyAim(InputAction.CallbackContext obj)
{
switch (obj)
{
case { interaction: PressInteraction, performed: true } when CurrentState is Aim:
isSteadyAim = true;
break;
case { interaction: PressInteraction, canceled: true }:
isSteadyAim = false;
break;
}
}
2023-09-01 14:33:54 +08:00
private void OnMovementCommand(object obj)
{
switch (obj)
{
case OnPlayerJumpCommand:
animator.Play("Jump");
break;
}
2023-08-23 01:59:40 +08:00
}
2023-08-27 02:58:19 +08:00
private void OnMelee(InputAction.CallbackContext obj)
{
switch (CurrentState)
{
case Equip:
case Melee:
return;
}
TransitionState<Melee>();
}
2023-08-23 01:59:40 +08:00
private void OnReload(InputAction.CallbackContext obj)
{
2023-08-27 02:58:19 +08:00
if (obj.JustPressed() is false) return;
switch (CurrentState)
{
case Equip:
case Melee:
return;
}
2023-08-23 01:59:40 +08:00
TransitionState<Reload>();
}
2023-06-08 14:09:50 +08:00
2023-08-23 01:59:40 +08:00
private void OnMovementStateChanged(IEntityMovementState arg1, IEntityMovementState arg2)
{
foreach (var x in StateDictionary.Values)
{
x.OnMovementStateChanged(arg1,arg2);
}
}
2023-10-20 19:31:12 +08:00
public override UniTask EntryAsync()
2023-06-08 14:09:50 +08:00
{
2023-10-20 19:31:12 +08:00
base.EntryAsync();
isHolstered = false;
inputActionGroup.allowInput.AddElement(this);
2023-08-23 01:59:40 +08:00
expectFiring.Reset();
Enabled = true;
2023-06-08 14:09:50 +08:00
2023-10-31 18:07:15 +08:00
fireInterval.Interval = 1f / _gun.FireMode.FireRate;
2023-08-23 01:59:40 +08:00
fireInterval.Reset();
2023-06-08 14:09:50 +08:00
2023-10-31 18:07:15 +08:00
if (_gun.FireMode is BurstFireMode burstFireMode)
2023-06-08 14:09:50 +08:00
{
2023-08-23 01:59:40 +08:00
burstFireInterval.Interval = burstFireMode.BurstFireInterval;
burstFireInterval.Reset();
2023-06-08 14:09:50 +08:00
}
2023-10-20 19:31:12 +08:00
TransitionState<Equip>();
return UniTask.CompletedTask;
2023-06-08 14:09:50 +08:00
}
2023-10-20 19:31:12 +08:00
public override async UniTask ExitAsync()
2023-06-08 14:09:50 +08:00
{
2023-10-20 19:31:12 +08:00
TransitionState<Holster>();
2023-10-31 18:07:15 +08:00
_equipService.AllowAttack = false;
2023-10-20 19:31:12 +08:00
inputActionGroup.allowInput.RemoveElement(this);
expectFiring.Reset();
cameraView.localPosition = default;
try
{
while (_health.IsAlive && isHolstered is false)
{
destroyCancellationToken.ThrowIfCancellationRequested();
2023-10-31 18:07:15 +08:00
_equipService.Zoom.Value = Mathf.MoveTowards(_equipService.Zoom.Value,0,Time.deltaTime);
2023-10-20 19:31:12 +08:00
await UniTask.NextFrame();
}
2023-10-31 18:07:15 +08:00
_equipService.Zoom.Allow = false;
2023-10-20 19:31:12 +08:00
destroyCancellationToken.ThrowIfCancellationRequested();
2023-10-31 18:07:15 +08:00
_equipService.Stable = 1;
2023-10-20 19:31:12 +08:00
await base.ExitAsync();
}
catch (OperationCanceledException)
2023-06-08 14:09:50 +08:00
{
}
}
public override void OnUpdate(float deltaTime)
{
2023-10-20 19:31:12 +08:00
UpdateState(deltaTime);
2023-10-31 18:07:15 +08:00
switch (_gun.FireMode)
2023-06-08 14:09:50 +08:00
{
2023-08-27 02:58:19 +08:00
case AutoFireMode:
break;
case SemiFireMode:
break;
case BurstFireMode when expectFiring.being:
expectFiring.shouldBe = fireAction.action.WasPressedThisFrame();
if(burstFireInterval.AllowUpdate)
{
2023-10-31 18:07:15 +08:00
switch (AnimationProperties.TryGetValue(BITConstant.Player.AllowFire, out var allowFire))
{
case false:
case true when allowFire >0.9f:
Fire();
break;
}
2023-08-27 02:58:19 +08:00
}
break;
2023-06-08 14:09:50 +08:00
}
2023-09-01 14:33:54 +08:00
animator.animator.SetBool(IsGrounded,_movement.IsGrounded);
2023-11-21 18:05:18 +08:00
animator.animator.SetBool(IsCrouched,_movement.CurrentState is IPlayerCrouchState or IPlayerSlideState);
2023-10-20 19:31:12 +08:00
animator.animator.SetFloat(BITConstant.Player.SqrMagnitude,_movement.LocomotionBasedVelocity.sqrMagnitude);
2023-09-01 14:33:54 +08:00
recoilSpring.Update(deltaTime,default);
locationAdditive.AddEuler(recoilSpring.value);
2023-11-15 23:54:54 +08:00
if (selfViewAdditive)
{
2023-11-21 18:05:18 +08:00
var positionWeight = recoilPositionWeight;
if (AnimationProperties.TryGetValue(BITConstant.Player.Aim, out var aim))
{
positionWeight *= Mathf.Lerp(2, 1, aim);
}
2023-11-15 23:54:54 +08:00
selfViewAdditive.AddEuler(recoilSpring.value);
selfViewAdditive.AddPosition(
new Vector3(
recoilSpring.value.y,
-recoilSpring.value.x,
recoilSpring.value.z
) *
2023-11-21 18:05:18 +08:00
positionWeight
2023-11-15 23:54:54 +08:00
);
}
2023-10-31 18:07:15 +08:00
if(AnimationProperties.TryGetValue(BITConstant.Player.Aim, out var _aim))
{
_equipService.Zoom.Allow = CurrentState is Aim;
2023-11-02 20:58:55 +08:00
_equipService.Zoom.Value =Mathf.Lerp(1,_gun.InitialAimZoom, _aim);
2023-10-31 18:07:15 +08:00
_equipService.AllowScope = _aim > 0.86f && _gun.IsScopeAim;
2023-11-02 20:58:55 +08:00
if (breathingAdditive.Allow)
{
var breatheFrequency = 0.5f; // 呼吸的频率,值越大呼吸越快
var breatheAmplitude = 0.005f; // 呼吸的幅度,即准星上下移动的最大距离
if (_playerMovement.Stamina <= 8)
{
breatheFrequency = 8;
breatheAmplitude = 0.1f;
}
var breatheOffset = Mathf.Sin(Time.time * breatheFrequency) * breatheAmplitude;
if (isSteadyAim)
{
if (_playerMovement.Stamina > 0)
{
_playerMovement.Stamina -= 16 * deltaTime;
breatheOffset *= 0.16f;
}
else
{
isSteadyAim = false;
}
}
else
{
breatheOffset *= _aim;
}
_playerMovement.AddViewEuler(new float2(breatheOffset, breatheOffset));
}
if (newSight.Allow)
{
transform.localPosition=Vector3.Lerp(default, newSight.Value.position-initialSight.position, _aim);
}
else
{
transform.localPosition = default;
}
2023-10-31 18:07:15 +08:00
}
if (AnimationProperties.TryGetValue(BITConstant.Player.Stable, out var stable))
{
_equipService.Stable = stable;
}
if(AnimationProperties.TryGetValue(BITConstant.Player.AllowFire, out var _allowFire))
{
_equipService.AllowAttack = _allowFire > 0.9f;
}
AllowRendering.SetDisableElements(64564,_equipService.AllowScope);
2023-11-15 23:54:54 +08:00
expectAiming.shouldBe = inputActionGroup.GetAction(aimAction).IsPressed();
2023-06-08 14:09:50 +08:00
}
2023-11-02 20:58:55 +08:00
2023-08-27 02:58:19 +08:00
public override void AnimationEvent(string eventName)
{
2023-10-20 19:31:12 +08:00
if(IsEntered is false) return;
2023-11-21 18:05:18 +08:00
base.AnimationEvent(eventName);
2023-08-27 02:58:19 +08:00
CurrentState?.AnimationEvent(eventName);
2023-11-21 18:05:18 +08:00
// switch (eventName)
// {
// case "Melee":
// meleeService.Melee(new MeleeCommand
// {
// PlayerId = Entity.Id,
// Position = Transform.position,
// Force = Transform.forward * 128,
// Range = 1
// });
// break;
// }
2023-08-27 02:58:19 +08:00
}
2023-06-08 14:09:50 +08:00
public void Fire()
{
2023-10-31 18:07:15 +08:00
if (RequireBolt) return;
2023-11-15 23:54:54 +08:00
2023-06-08 14:09:50 +08:00
//播放射击动画
2023-10-29 15:27:13 +08:00
UnityEntity.Invoke(Constant.Animation.Play, BITConstant.Player.Fire);
2023-06-08 14:09:50 +08:00
2023-11-15 23:54:54 +08:00
if (_gun.BuckShot.Allow)
2023-06-08 14:09:50 +08:00
{
2023-11-15 23:54:54 +08:00
InternalAddRecoil();
for (int i = 0; i < _gun.BuckShot.Value; i++)
{
InternalFire();
}
}
else
{
InternalFire();
InternalAddRecoil();
}
2023-06-08 14:09:50 +08:00
//开火模式逻辑判断
2023-10-31 18:07:15 +08:00
switch (_gun.FireMode)
2023-06-08 14:09:50 +08:00
{
case AutoFireMode:
break;
case SemiFireMode:
//如果是半自动开火,则取消射击
2023-08-23 01:59:40 +08:00
expectFiring.Reset();
2023-06-08 14:09:50 +08:00
break;
case BurstFireMode burstFireMode:
burstFireCount++;
2023-08-23 01:59:40 +08:00
expectFiring.being = true;
2023-06-08 14:09:50 +08:00
if(burstFireCount > burstFireMode.BurstRound)
{
burstFireCount = 0;
2023-08-23 01:59:40 +08:00
expectFiring.Reset();
2023-06-08 14:09:50 +08:00
}
break;
}
2023-11-15 23:54:54 +08:00
if (_gun.FireMode is SemiFireMode {RequireBoltAction:true})
{
RequireBolt = true;
}
}
private void InternalFire()
{
//调用BulletManager生成子弹
var _transform = transform;
var rotation = _transform.rotation;
var random = UnityEngine.Random.insideUnitCircle;
if (_gun.TryGetProperty<ISpread>(out var spread))
{
random *= spread.Spread;
}
2023-11-21 18:05:18 +08:00
if(AnimationProperties.TryGetValue(BITConstant.Player.Aim, out var aim))
{
random *= Mathf.Lerp(_gun.InitialHipFireSpread,1,aim);
}
2023-11-15 23:54:54 +08:00
random *= recoilSpring.value.GetLength();
BulletService.Spawn(new SpawnBullet
{
Initiator = Entity.Id,
Position = (_transform.position+rotation * bulletInitialOffset),
Rotation = rotation,
Forward = rotation * (Vector3.forward + Vector3.up * random.y + Vector3.right * random.x),
InitialDamage = _gun.InitialDamage,
StartSpeed = _gun.InitialBulletSpeed,
InitialForce = _gun.InitialBulletForce,
});
}
private void InternalAddRecoil()
{
2023-10-31 18:07:15 +08:00
if (_gun.TryGetProperty<IRecoil>(out var _recoil))
2023-09-01 14:33:54 +08:00
{
var _newRecoil = new Vector3
{
x = _recoil.Recoil.x,
y = _recoil.Recoil.y.Random(),
z = _recoil.Recoil.z.Random()
};
recoilSpring.value = _newRecoil;
_playerMovement.AddViewEuler(new float2(_newRecoil.x,_newRecoil.y));
}
2023-06-08 14:09:50 +08:00
}
2023-08-23 01:59:40 +08:00
private void OnFire(InputAction.CallbackContext context)
2023-06-08 14:09:50 +08:00
{
2023-11-15 23:54:54 +08:00
//如果启用了指针则不开火
if(BITAppForUnity.AllowCursor)
{
expectFiring.Reset();
return;
}
2023-10-31 18:07:15 +08:00
switch (_gun.FireMode)
2023-10-24 23:37:59 +08:00
{
case AutoFireMode :
switch (context)
{
2023-11-02 20:58:55 +08:00
case {interaction:PressInteraction , started:true}:
2023-10-24 23:37:59 +08:00
expectFiring.shouldBe = true;
break;
2023-11-02 20:58:55 +08:00
case {interaction:PressInteraction , canceled:true}:
2023-10-24 23:37:59 +08:00
expectFiring.shouldBe = false;
break;
}
break;
case SemiFireMode:
switch (context)
{
2023-11-02 20:58:55 +08:00
case { interaction: PressInteraction, started: true } when fireInterval.AllowUpdateWithoutReset && RequireBolt is false:
2023-10-24 23:37:59 +08:00
expectFiring.shouldBe = true;
break;
}
break;
}
2023-06-08 14:09:50 +08:00
}
2023-08-23 01:59:40 +08:00
private void OnAim(InputAction.CallbackContext context)
2023-06-08 14:09:50 +08:00
{
2023-11-15 23:54:54 +08:00
//如果启用了指针则不开火
if(BITAppForUnity.AllowCursor)
{
expectAiming.Reset();
return;
}
//expectAiming.shouldBe = context.ReadValueAsButton();
2023-06-08 14:09:50 +08:00
}
}
2023-11-15 23:54:54 +08:00
// #if UNITY_EDITOR
// [CustomEditor(typeof(BITGun))]
// public class BITGunInspector:BITInspector<BITGun>{}
// #endif
2023-06-08 14:09:50 +08:00
}