A Simple Vertex Shader

In game development knowing how to write vertex shader is of utmost importance. Vertex shaders could be used to generate terrain,animate foliage,water,fishes etc to name a few. Today we are going to write a very basic vertex shader which could be the basis for a more advanced once. For this tutorial you are going to need a subdivided plane mesh the vertices of which will be used for this shader. You can generate this mesh in any modelling program such as Blender by adding a plane and subdividing it many times so that we have many vertices to work with. With that out of the way lets start by writing our shader. We are going to use the Godot game engine and the first thing you need to do is adding the plane mesh to your scene and assigning a shader to it. The scene looks like this at the beginning..

Capture
A Plane mesh which has been subdivided many times

Our shader looks like this…

shader_type spatial;

void vertex()
{

}

The line shader_type spatial indicates that this shader is meant for a three dimensional object. The vertex function is where all the magic will take place. Let’s modify our vertex function so that our shader program looks like this now…

shader_type spatial;
uniform sampler2D noise;

void vertex()
{
	VERTEX.y+=texture(noise,UV).g;
}
Capture 1
The vertices are displaced by reading noise values from a noise texture

Okay as you can see the vertices that make up the plane are being displaced by a random amount in the y-direction. How is this happening you ask? Well did you notice the noise uniform at the beginning? We are assigning a noise texture to the material and reading noise values from it. The line term texture(noise,UV).g is used to read from the green channel of the noise texture and this value is added to the y-values of the vertices thereby displacing them by a random amount. This shader right here could be considered to be the basis for a very crude terrain shader. But wait what if we could make it more smooth, can we? Well yes we can, once again bringing cos and sin to our rescue. Modify the shader so that it looks like this now..

shader_type spatial;

void vertex()
{
  VERTEX.y+=cos(VERTEX.x*5.)*sin(VERTEX.z*5.);
}

And now the plane looks like rolling hills…

Capture 2

Now let’s animate this by making the hills move…This could be considered anything you could imagine water waves, visualization for music albeit a very crude one but it’s a start isn’t it?

waves 3
ezgif.com gif maker1

shader_type spatial;
void vertex()
{
   VERTEX.y+=cos(TIME*VERTEX.x*5.)*sin(TIME*VERTEX.z*5.);
}

Hope that was fun. Until next time,cheers!

Related :

Follow :