AttackState.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value.
  3. using UnityEngine;
  4. namespace Animancer.Samples.StateMachines
  5. {
  6. /// <summary>A <see cref="CharacterState"/> which can perform <see cref="Weapon.AttackAnimations"/> in sequence.</summary>
  7. ///
  8. /// <remarks>
  9. /// <strong>Sample:</strong>
  10. /// <see href="https://kybernetik.com.au/animancer/docs/samples/fsm/weapons">
  11. /// Weapons</see>
  12. /// </remarks>
  13. ///
  14. /// https://kybernetik.com.au/animancer/api/Animancer.Samples.StateMachines/AttackState
  15. ///
  16. [AddComponentMenu(Strings.SamplesMenuPrefix + "Weapons - Attack State")]
  17. [AnimancerHelpUrl(typeof(AttackState))]
  18. public class AttackState : CharacterState
  19. {
  20. /************************************************************************************************************************/
  21. private int _AttackIndex = int.MaxValue;
  22. private AnimancerState _CurrentState;
  23. public Weapon Weapon
  24. => Character.Equipment.Weapon;
  25. /************************************************************************************************************************/
  26. public override bool CanEnterState
  27. => Weapon != null
  28. && Weapon.AttackAnimations.Length > 0;
  29. public override CharacterStatePriority Priority
  30. => CharacterStatePriority.Medium;
  31. /************************************************************************************************************************/
  32. protected virtual void OnEnable()
  33. {
  34. // Start at the beginning of the sequence by default,
  35. // but if the previous attack has not faded out yet
  36. // then perform the next attack instead.
  37. if (ShouldRestartCombo)
  38. _AttackIndex = 0;
  39. else
  40. _AttackIndex++;
  41. TransitionAsset animation = Weapon.AttackAnimations[_AttackIndex];
  42. _CurrentState = Character.Animancer.Play(animation);
  43. _CurrentState.Events(this).OnEnd ??= Character.StateMachine.ForceSetDefaultState;
  44. }
  45. /************************************************************************************************************************/
  46. private bool ShouldRestartCombo
  47. => _AttackIndex >= Weapon.AttackAnimations.Length - 1
  48. || _CurrentState == null
  49. || _CurrentState.Weight == 0;
  50. /************************************************************************************************************************/
  51. }
  52. }