Guest User

Untitled

a guest
Oct 17th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. // Creates a Unity Mesh that contains a wavy 2D surface, then animates that surface.
  2. // Based on grid.cs (except now in the X/Z plane), gives each vertex a different height using Sin & Cos.
  3. // Should be attached to a GameObject that already has a MeshFilter component.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7.  
  8. public class waves : MonoBehaviour {
  9.  
  10. public int numRows=10, numCols=10;
  11. public float minX=-1, maxX=1, minZ=-1, maxZ=1;
  12. public float height=0.1f;
  13. private Vector3[] myVerts;
  14.  
  15. void Start ()
  16. {
  17. int index;
  18. myVerts = new Vector3[numRows*numCols];
  19. index = 0;
  20. for (int j=0; j < numRows; j++)
  21. for (int i=0; i < numCols; i++)
  22. {
  23. float x = Mathf.Lerp(minX,maxX,i/(numCols-1f));
  24. float z = Mathf.Lerp(minZ,maxZ,j/(numRows-1f));
  25. float y = Mathf.Sin(x*5f) * Mathf.Cos(z*5f) * height;
  26. myVerts[index] = new Vector3(x,y,z);
  27. index++;
  28. }
  29. int[] myTris = new int[(numRows-1)*(numCols-1)*2*3];
  30. index = 0;
  31. for (int j=0; j < numRows-1; j++)
  32. for (int i=0; i < numCols-1; i++)
  33. {
  34. myTris[index++] = i + j*numCols;
  35. myTris[index++] = i + (j+1)*numCols;
  36. myTris[index++] = (i+1) + j*numCols;
  37. myTris[index++] = i + (j+1)*numCols;
  38. myTris[index++] = (i+1) + (j+1)*numCols;
  39. myTris[index++] = (i+1) + j*numCols;
  40. }
  41. Mesh myMesh = gameObject.GetComponent<MeshFilter>().mesh;
  42. myMesh.Clear();
  43. myMesh.vertices = myVerts;
  44. myMesh.triangles = myTris;
  45. myMesh.RecalculateNormals();
  46. }
  47.  
  48. void Update ()
  49. {
  50. int index = 0;
  51. for (int j=0; j < numRows; j++)
  52. for (int i=0; i < numCols; i++)
  53. {
  54. float x = myVerts[index].x;
  55. float z = myVerts[index].z;
  56. float y = Mathf.Sin(x*5f+Time.time) * Mathf.Cos(z*5f+Time.time/3f) * height;
  57. myVerts[index] = new Vector3(x,y,z);
  58. index++;
  59. }
  60. Mesh myMesh = gameObject.GetComponent<MeshFilter>().mesh;
  61. myMesh.vertices = myVerts;
  62. myMesh.RecalculateNormals();
  63. }
  64. }
Add Comment
Please, Sign In to add comment