TesselatedWater.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // ShaderGraphEssentials for Unity
  3. // (c) 2019 PH Graphics
  4. // Source code may be used and modified for personal or commercial projects.
  5. // Source code may NOT be redistributed or sold.
  6. //
  7. // *** A NOTE ABOUT PIRACY ***
  8. //
  9. // If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store.
  10. //
  11. // I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software.
  12. //
  13. // Thank you.
  14. //
  15. // *** END NOTE ABOUT PIRACY ***
  16. //
  17. using UnityEngine;
  18. namespace ShaderGraphEssentials
  19. {
  20. [System.Serializable]
  21. public class NoiseOctaveData
  22. {
  23. public Vector2 Direction;
  24. public float Amplitude = 1f;
  25. public float Speed = 1f;
  26. public float Frequency = 1f;
  27. }
  28. public class TesselatedWater : MonoBehaviour
  29. {
  30. // disable "not assigned" warning because it is assigned by the editor
  31. #pragma warning disable 0649
  32. [SerializeField]
  33. private NoiseOctaveData[] _noiseOctaveData;
  34. [SerializeField]
  35. private MeshFilter _waterGrid;
  36. #pragma warning restore 0649
  37. private Mesh _waterMesh;
  38. private Vector3[] _vertices;
  39. void Start()
  40. {
  41. _waterMesh = _waterGrid.mesh;
  42. _vertices = _waterMesh.vertices;
  43. }
  44. void Update()
  45. {
  46. for (int i = 0; i < _vertices.Length; i++)
  47. {
  48. var position = _vertices[i];
  49. float height = 0f;
  50. foreach (var data in _noiseOctaveData)
  51. {
  52. Vector2 direction = data.Direction.normalized;
  53. height += data.Amplitude * Mathf.Sin(Time.time * data.Speed + data.Frequency * (position.x * direction.x + position.z * direction.y));
  54. }
  55. _vertices[i] = new Vector3(position.x, height, position.z);
  56. }
  57. _waterMesh.vertices = _vertices;
  58. _waterMesh.RecalculateNormals();
  59. }
  60. }
  61. }