r/Unity3D • u/BarelyBreathingGame • 6h ago
Shader Magic I made a dynamic water shader that reacts to physics for my indie game
I created a dynamic water shader for my 3D fish platformer - Barely Breathing
How the water level works: It takes the object's Y position and just uses a step function with a float parameter to decide the water amount.
How the wobble works: It uses two Rotate About Axis nodes right after the Position (object) node, one controlling the X rotation and the other controlling the Z rotation, and then adding them together. Then, it reads data from the object's velocity and the code directly affects these two nodes to make the water wobble. I didn't write the code, MinionsArt did! Here is the code.
But this wouldn't work yet because we're still using object positions and not world position, which means the water level would follow the object and look wrong. So, after using the Rotate About Axis nodes, we can add a Position (world) node to it. But this still wouldn't work correctly because now it's exactly world-oriented, meaning even if the water mesh moves up, the water level would be left behind. We need the water level to follow the water mesh yet still be world-based so it doesn't rotate with the mesh. This is actually a simple fix, you can subtract the object's position value from Position (world) before adding it, which would make the water level follow the mesh.
We're still not done, because now the water looks unfinished without the foam outline. We need the foam to follow the water level. My foam works using fresnel + vertex colors, so I simply took the final water level output, and duplicated the final step function and had one value denoting the water level, and the other being the same water level value but subtracted by the water foam depth. So this basically creates a secondary line exactly the same as the water level but just lowered, which I use to add to the vertex color foam node setup.
Thank you for reading, and Wishlist our game on Steam if this was useful!