SetWaterHeight.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. public class SetWaterHeight : MonoBehaviour
  4. {
  5. public Transform Target;
  6. private MeshRenderer m;
  7. private Material material;
  8. private Vector3 LastPos;
  9. private List<float> ArrLastPos;
  10. private float force;
  11. private float damp;
  12. private float JitterScale;
  13. // Use this for initialization
  14. void Start()
  15. {
  16. m = transform.GetComponent<MeshRenderer>();
  17. if (m != null) material = m.material;
  18. LastPos = transform.position;
  19. ArrLastPos = new List<float>();
  20. }
  21. // Update is called once per frame
  22. void Update()
  23. {
  24. if (material != null && Target != null)
  25. {
  26. __SetCurrentPos();
  27. __TheJitter();
  28. }
  29. if (Input.GetMouseButtonDown(0))
  30. {
  31. damp = 0.3f;
  32. }
  33. }
  34. /// <summary>
  35. /// 设置当前位置
  36. /// </summary>
  37. private void __SetCurrentPos()
  38. {
  39. material.SetFloat("_LevelOfWaterX", Target.position.x);
  40. material.SetFloat("_LevelOfWaterY", Target.position.y);
  41. material.SetFloat("_LevelOfWaterZ", Target.position.z);
  42. }
  43. /// <summary>
  44. /// 抖动计算
  45. /// </summary>
  46. private void __TheJitter()
  47. {
  48. //顺序不可变
  49. if (transform.position == LastPos && ArrLastPos.Count != 0)
  50. {
  51. float distance = 0;
  52. for (int i = 0; i < ArrLastPos.Count; i++)
  53. {
  54. distance += ArrLastPos[i];
  55. }
  56. distance /= ArrLastPos.Count;
  57. damp = distance * 15f;
  58. ArrLastPos = new List<float>();
  59. }
  60. if (transform.position != LastPos)
  61. {
  62. ArrLastPos.Add(Vector3.Distance(transform.position, LastPos));
  63. LastPos = transform.position;
  64. }
  65. if (damp != 0)
  66. {
  67. force += 0.5f;
  68. if (damp < 0.005f)
  69. {
  70. damp = 0;
  71. }
  72. JitterScale = Mathf.Sin(force) * damp;
  73. material.SetFloat("_LevelOfWaterOffsetScale", JitterScale);
  74. damp *= 0.95f;
  75. }
  76. }
  77. }