Dumper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using UnityEngine;
  3. namespace Assets.Scripts.Dumper
  4. {
  5. internal sealed class Dumper : MonoBehaviour
  6. {
  7. public bool ChangeStartPosition;
  8. public AnimationCurve DumpingOverTime = AnimationCurve.Linear(0, 1, 1, 1);
  9. public float Fps = 30;
  10. public float LifeTime = 4f;
  11. private Vector3 _originalStartPosition;
  12. private float _animationStartTime;
  13. private bool _isCoCanceled;
  14. private bool _isCoStarted;
  15. private void Start()
  16. {
  17. StartEffect();
  18. }
  19. private void StartEffect()
  20. {
  21. if (_isCoStarted)
  22. return;
  23. Invoke("StopEffect", LifeTime);
  24. _isCoCanceled = false;
  25. _originalStartPosition = transform.position;
  26. StartCoroutine(UpdateCorutine());
  27. }
  28. private IEnumerator UpdateCorutine()
  29. {
  30. _isCoStarted = true;
  31. _animationStartTime = Time.time;
  32. while (!_isCoCanceled)
  33. {
  34. var frameTime = Time.time - _animationStartTime;
  35. if (frameTime >= LifeTime)
  36. break;
  37. var currentDump = DumpingOverTime.Evaluate(frameTime);
  38. var newX = Random.Range(_originalStartPosition.x - currentDump, _originalStartPosition.x + currentDump);
  39. var newY = Random.Range(_originalStartPosition.y - currentDump, _originalStartPosition.y + currentDump);
  40. var newZ = Random.Range(_originalStartPosition.z - currentDump, _originalStartPosition.z + currentDump);
  41. transform.position = new Vector3(newX, newY, newZ);
  42. yield return new WaitForSeconds(1f / Fps);
  43. }
  44. }
  45. private void StopEffect()
  46. {
  47. _isCoCanceled = true;
  48. StopAllCoroutines();
  49. _isCoStarted = false;
  50. }
  51. private void OnDestroy()
  52. {
  53. StopEffect();
  54. }
  55. }
  56. }