Create a gist now

Instantly share code, notes, and snippets.

Embed
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