HitReceiver.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Animancer.Units;
  4. using System;
  5. using Unity.Collections;
  6. using UnityEngine;
  7. using UnityEngine.Animations;
  8. namespace Animancer.Samples.Jobs
  9. {
  10. /// <summary>
  11. /// An sample component that demonstrates how <see cref="SimpleLean"/>
  12. /// can be used as a dynamic response to getting hit.
  13. /// </summary>
  14. ///
  15. /// <remarks>
  16. /// <strong>Sample:</strong>
  17. /// <see href="https://kybernetik.com.au/animancer/docs/samples/jobs/hit-impacts">
  18. /// Hit Impacts</see>
  19. /// </remarks>
  20. ///
  21. /// https://kybernetik.com.au/animancer/api/Animancer.Samples.Jobs/HitReceiver
  22. ///
  23. [AddComponentMenu(Strings.SamplesMenuPrefix + "Jobs - Hit Receiver")]
  24. [AnimancerHelpUrl(typeof(HitReceiver))]
  25. public class HitReceiver : MonoBehaviour
  26. {
  27. /************************************************************************************************************************/
  28. [SerializeField] private AnimancerComponent _Animancer;
  29. [SerializeField] private Transform[] _Bones;
  30. [SerializeField, Degrees] private float _MaximumAngle = 45;
  31. [SerializeField, Seconds] private float _SmoothingTime = 0.25f;
  32. private SimpleLean _Lean;
  33. private float _Speed;
  34. /************************************************************************************************************************/
  35. protected virtual void Awake()
  36. {
  37. Debug.Assert(_Bones.Length > 0, "No bones are assigned.", this);
  38. NativeArray<TransformStreamHandle> boneHandles =
  39. AnimancerUtilities.ConvertToTransformStreamHandles(_Bones, _Animancer.Animator);
  40. _Lean = new(_Animancer.Graph, Vector3.right, boneHandles);
  41. }
  42. /************************************************************************************************************************/
  43. public void Hit(Vector3 direction, float force)
  44. {
  45. _Lean.Axis = Vector3.Cross(Vector3.up, direction).normalized;
  46. _Speed = force;
  47. enabled = true;
  48. }
  49. /************************************************************************************************************************/
  50. protected virtual void Update()
  51. {
  52. float angle = Mathf.SmoothDamp(_Lean.Angle, 0, ref _Speed, _SmoothingTime);
  53. angle = Math.Min(angle, _MaximumAngle);
  54. _Lean.Angle = angle;
  55. if (angle == 0 && _Speed == 0)
  56. enabled = false;
  57. }
  58. /************************************************************************************************************************/
  59. }
  60. }