StressReceiver.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
  2. using UnityEngine;
  3. public class StressReceiver : MonoBehaviour
  4. {
  5. public float trauma;
  6. private float _trauma;
  7. private Vector3 _lastPosition;
  8. private Vector3 _lastRotation;
  9. [Tooltip("Exponent for calculating the shake factor. Useful for creating different effect fade outs")]
  10. public float TraumaExponent = 1;
  11. [Tooltip("Maximum angle that the gameobject can shake. In euler angles.")]
  12. public Vector3 MaximumAngularShake = Vector3.one * 5;
  13. [Tooltip("Maximum translation that the gameobject can receive when applying the shake effect.")]
  14. public Vector3 MaximumTranslationShake = Vector3.one * .75f;
  15. [ContextMenu("asdasda")]
  16. public void Test()
  17. {
  18. InduceStress(trauma);
  19. }
  20. private void Update()
  21. {
  22. float shake = Mathf.Pow(_trauma, TraumaExponent);
  23. /* Only apply this when there is active trauma */
  24. if(shake > 0)
  25. {
  26. var previousRotation = _lastRotation;
  27. var previousPosition = _lastPosition;
  28. /* In order to avoid affecting the transform current position and rotation each frame we substract the previous translation and rotation */
  29. _lastPosition = new Vector3(
  30. MaximumTranslationShake.x * (Mathf.PerlinNoise(0, Time.time * 25) * 2 - 1),
  31. MaximumTranslationShake.y * (Mathf.PerlinNoise(1, Time.time * 25) * 2 - 1),
  32. MaximumTranslationShake.z * (Mathf.PerlinNoise(2, Time.time * 25) * 2 - 1)
  33. ) * shake;
  34. _lastRotation = new Vector3(
  35. MaximumAngularShake.x * (Mathf.PerlinNoise(3, Time.time * 25) * 2 - 1),
  36. MaximumAngularShake.y * (Mathf.PerlinNoise(4, Time.time * 25) * 2 - 1),
  37. MaximumAngularShake.z * (Mathf.PerlinNoise(5, Time.time * 25) * 2 - 1)
  38. ) * shake;
  39. transform.localPosition += _lastPosition - previousPosition;
  40. transform.localRotation = Quaternion.Euler(transform.localRotation.eulerAngles + _lastRotation - previousRotation);
  41. _trauma = Mathf.Clamp01(_trauma - Time.deltaTime);
  42. }
  43. else
  44. {
  45. if (_lastPosition == Vector3.zero && _lastRotation == Vector3.zero) return;
  46. /* Clear the transform of any left over translation and rotations */
  47. transform.localPosition -= _lastPosition;
  48. transform.localRotation = Quaternion.Euler(transform.localRotation.eulerAngles - _lastRotation);
  49. _lastPosition = Vector3.zero;
  50. _lastRotation = Vector3.zero;
  51. }
  52. }
  53. /// <summary>
  54. /// Applies a stress value to the current object.
  55. /// </summary>
  56. /// <param name="Stress">[0,1] Amount of stress to apply to the object</param>
  57. public void InduceStress(float Stress)
  58. {
  59. _trauma = Mathf.Clamp01(_trauma + Stress);
  60. }
  61. }