Skip to content

Instantly share code, notes, and snippets.

@davepape davepape/waves.cs
Created Oct 17, 2018

Embed
What would you like to do?
Create simple animated waves
// Creates a Unity Mesh that contains a wavy 2D surface, then animates that surface.
// Based on grid.cs (except now in the X/Z plane), gives each vertex a different height using Sin & Cos.
// Should be attached to a GameObject that already has a MeshFilter component.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class waves : MonoBehaviour {
public int numRows=10, numCols=10;
public float minX=-1, maxX=1, minZ=-1, maxZ=1;
public float height=0.1f;
private Vector3[] myVerts;
void Start ()
{
int index;
myVerts = new Vector3[numRows*numCols];
index = 0;
for (int j=0; j < numRows; j++)
for (int i=0; i < numCols; i++)
{
float x = Mathf.Lerp(minX,maxX,i/(numCols-1f));
float z = Mathf.Lerp(minZ,maxZ,j/(numRows-1f));
float y = Mathf.Sin(x*5f) * Mathf.Cos(z*5f) * height;
myVerts[index] = new Vector3(x,y,z);
index++;
}
int[] myTris = new int[(numRows-1)*(numCols-1)*2*3];
index = 0;
for (int j=0; j < numRows-1; j++)
for (int i=0; i < numCols-1; i++)
{
myTris[index++] = i + j*numCols;
myTris[index++] = i + (j+1)*numCols;
myTris[index++] = (i+1) + j*numCols;
myTris[index++] = i + (j+1)*numCols;
myTris[index++] = (i+1) + (j+1)*numCols;
myTris[index++] = (i+1) + j*numCols;
}
Mesh myMesh = gameObject.GetComponent<MeshFilter>().mesh;
myMesh.Clear();
myMesh.vertices = myVerts;
myMesh.triangles = myTris;
myMesh.RecalculateNormals();
}
void Update ()
{
int index = 0;
for (int j=0; j < numRows; j++)
for (int i=0; i < numCols; i++)
{
float x = myVerts[index].x;
float z = myVerts[index].z;
float y = Mathf.Sin(x*5f+Time.time) * Mathf.Cos(z*5f+Time.time/3f) * height;
myVerts[index] = new Vector3(x,y,z);
index++;
}
Mesh myMesh = gameObject.GetComponent<MeshFilter>().mesh;
myMesh.vertices = myVerts;
myMesh.RecalculateNormals();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.