Remember when your high school math teacher used to talk about sine and cosine waves? Remember when you thought you weren't ever going to use them again? I do. Sitting in math class this week, I realized the last surfing video game I played was for the PS1, and I wondered why they weren't made anymore. This got me thinking: how could I implement a wave system in Unity. I've used the water that you can import, and mesh with shaders. The prefab assets can fit for a lake, or pond, though I only ran into one prefab that had waves. Upon thinking about how I could implement something similar, I remembered the sine wave.I figured if I could access the vertices of a plane, I could adjust their height with a sin wave over time, that would replicate ocean waves. The variables I used to modify the waves were waveSpeed (Speed the wave travels), waveHeight (height of the wave), and waveFrequency (How many waves appear within the plane). NoiseStrength changes how high above the original flat plane the vertices are. Noise walk changes the differences in the wave from side to side.
The first thing I did was create an Vector3 array to hold the vertices in the water mesh: Vector3[] WaterVertices = new Vector3[baseHeight.Length]; The next thing I did was to loop through every vertex and adjust the height. Along with adjusting the height with the sin wave, I added Perlin Noise, which makes the wave look imperfect. When each wave is produced, we don't want the whole wave to look identical. This helps make the wave look more realistic, replicating the wind over the ocean that makes it slightly choppy. for (int i=0; i< WaterVertices.Length; i++) //Go through each vertex and adjust the height. { Vector3 vert = baseHeight[i]; //Get the base height of the vertex. (Implent this for continuity within the wave.) Vector3 dir = rotation * vert; //Rotate //Ajust the height so they follow the sin wave. vert.y += Mathf.Sin(Time.time * waveSpeed+ dir.x + dir.y + dir.z * waveFrequency) * waveHeight; vert.y += Mathf.PerlinNoise (baseHeight [i].x + noiseWalk, baseHeight [i].y + Mathf.Sin (Time.time * 0.1f)) * noiseStrength; WaterVertices[i] = vert; //Reset the individual vertex. } The final thing to do was to reassign the new vertices to the water mesh, and then recalculate the normals of the mesh.
0 Comments
Leave a Reply. |
AuthorJuri Kiin is a Game Design & Development student at Rochester Institute of Technology Archives
January 2017
Categories |