Skip to content

Instantly share code, notes, and snippets.

@turbohermit
Last active September 7, 2017 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turbohermit/13e55ca1317fc0441f77d8a90f9bac02 to your computer and use it in GitHub Desktop.
Save turbohermit/13e55ca1317fc0441f77d8a90f9bac02 to your computer and use it in GitHub Desktop.
A simple vertex displacement script that uses sine on two axis to emulate a wave-like behaviour.
//A simple vertex displacement script that uses sine on two axis to emulate a wave-like behaviour.
public class WaveMesh : MonoBehaviour
{
public MeshFilter meshFilter;
public float amplitude = 0.5f;
public float xLength = 0.5f;
public float zLength = 0.5f;
public float speed = 1.0f;
//Only affect the vertices above this heigth in local space
public float affectedVerticesHeightTreshold;
//Offset vertices below this height with this:
public float unaffectedVerticesOffset;
private float[] originalHeight;
private Mesh targetMesh;
public void StoreMeshInfo()
{
targetMesh = meshFilter.mesh;
originalHeight = new float[targetMesh.vertexCount];
for (int i = 0; i < originalHeight.Length; i++)
{
originalHeight[i] = targetMesh.vertices[i].y;
}
}
public void UpdateMesh()
{
Vector3[] vertices = targetMesh.vertices;
for (int i = 0; i < vertices.Length; i++)
{
if (originalHeight[i] > affectedVerticesHeightTreshold)
{
vertices[i].y = Mathf.Sin((Time.time * speed) + (vertices[i].x * xLength) + (vertices[i].z * zLength) + originalHeight[i]) * amplitude;
}
else
{
vertices[i].y = -amplitude-unaffectedVerticesOffset;
}
}
targetMesh.vertices = vertices;
targetMesh.RecalculateNormals();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment