Thursday, February 22, 2024

GPU Instanced Grass in Unity - Part 2

GPU Instanced Grass in Unity


For the original post, please go to https://www.yuque.com/qwerasdwww/dfy5xd


Part 2: Add More Details to the Grass.


First, let's add some random rotation to the grass.

We define a new variable called maxLean to determine the range of the grass bending.

We will use this variable to determine how many degrees that the grass will rotate aroud z axis.




Create a new function called UpdateMaterialParameters() to update the lean value.

Call this function inside Update()



We also need to declare this variable inside compute shader and calculate the rotation value for each grass.



Create a rotation matrix in the V/F shader, use the lean as input angle.

We want to make the grass rotate more at the top, and less at the bottom, so add uv to control the rotation.




Now we can get random rotation around z axis for each grass. We can add x axis rotation to the rotation matrix later.



Now we want add some wind to the grass.

Declare the variables to control the wind in the C# script, and do the computation in the compute shader.



Let's first apply the time to grass rotation to simulate basic wind effect.



Now we get a simple movement.




Now let's add more interesting wind with perlin noise.

We use the head file "simplexNoise.cginc". The script is attached at the end of this section.

Please Check the detailed implementation on

https://github.com/ashima/webgl-noise




Now let's draw grass on terrains instead of planes.

Recall that we initialize the grass position and set y value to be 0 inside the InitComputeBufferr() function. We take that part out, create a new function called InitPositionsArray() and calculate y values there.


 



To calculate the y values, we shoot a ray downward, if the ray intersects with the terrain, then a grass is spwaned at the intersection position.


 


Now we successfully make grass spawn at any terrain we want.




No comments:

Post a Comment

common art sprint#6

 Added some per instance randomness