- Home /
Sinus for rolling waves
I got this script on a plane mesh doing some nice rolling waves however it looks a bit too perfect - the "waves" are rolling in one direction only. I'd like to add some noise to it
var scale = 10.0;
var speed = 1.0;
private var baseHeight : Vector3[];
function Update () {
var mesh : Mesh = GetComponent(MeshFilter).mesh;
if (baseHeight == null)
baseHeight = mesh.vertices;
var vertices = new Vector3[baseHeight.Length];
for (var i=0;i<vertices.Length;i++)
{
var vertex = baseHeight[i];
vertex.y += Mathf.Sin(Time.time * speed+ baseHeight[i].x + baseHeight[i].y + baseHeight[i].z) * scale;
vertices[i] = vertex;
}
mesh.vertices = vertices;
mesh.RecalculateNormals();
}
Answer by robertbu · Apr 22, 2013 at 04:31 PM
You can add some perlin noise to the waves:
#pragma strict
var scale = 10.0;
var speed = 1.0;
var noiseStrength = 4.0;
private var baseHeight : Vector3[];
function Update () {
var mesh : Mesh = GetComponent(MeshFilter).mesh;
if (baseHeight == null)
baseHeight = mesh.vertices;
var vertices = new Vector3[baseHeight.Length];
for (var i=0;i<vertices.Length;i++)
{
var vertex = baseHeight[i];
vertex.y += Mathf.Sin(Time.time * speed+ baseHeight[i].x + baseHeight[i].y + baseHeight[i].z) * scale;
vertex.y += Mathf.PerlinNoise(baseHeight[i].x + noiseWalk, baseHeight[i].y + Mathf.Sin(Time.time * 0.1) ) * noiseStrength;
vertices[i] = vertex;
}
mesh.vertices = vertices;
mesh.RecalculateNormals();
}
You could also combine two Sine calculations to modulate the height of the waves.
https://share.ehs.uen.org/node/19330
And you could use yet another Sine function to change the speed over time.
I converted it to C#
using UnityEngine;
using System.Collections;
public class WaveGen : $$anonymous$$onoBehaviour
{
float scale = 0.1f;
float speed = 1.0f;
float noiseStrength = 1f;
float noiseWalk = 1f;
private Vector3[] baseHeight;
void Update () {
$$anonymous$$esh mesh = GetComponent<$$anonymous$$eshFilter>().mesh;
if (baseHeight == null)
baseHeight = mesh.vertices;
Vector3[] vertices = new Vector3[baseHeight.Length];
for (int i=0;i<vertices.Length;i++)
{
Vector3 vertex = baseHeight[i];
vertex.y += $$anonymous$$athf.Sin(Time.time * speed+ baseHeight[i].x + baseHeight[i].y + baseHeight[i].z) * scale;
vertex.y += $$anonymous$$athf.PerlinNoise(baseHeight[i].x + noiseWalk, baseHeight[i].y + $$anonymous$$athf.Sin(Time.time * 0.1f) ) * noiseStrength;
vertices[i] = vertex;
}
mesh.vertices = vertices;
mesh.RecalculateNormals();
}
}
Answer by sfjuocekr · Nov 22, 2015 at 12:40 AM
Add at the end of the update function to update the MeshCollider:
GetComponent().sharedMesh = mesh;
However, changing a static collider like this is very intensive for physics. So I suggest adding a kinematic Rigidbody.
Your answer
Follow this Question
Related Questions
Wave formula(s) (math) 1 Answer
How can I make water waves ? 1 Answer
JS: Dump array value in an Enum 1 Answer
increase speed every spawn wave 0 Answers
How do I simulate a tsunami wave? 6 Answers