2D Water Simulation21 Jun 2014
A demo of a simple water simulation
Click above the surface to drop a rock.
I wanted to create a water simulation, something that I could perhaps use in games. Using the spring object I showed in this post I could quickly put together something that resembles a water surface. I achieved this by lining a row of vertical springs with natural length of the height of the water, and connecting all adjacent points at the surface with horizontal springs.
Showing the demo in a kind of 'debug' mode you can clearly see the spring setup. You can also click and drag the points to affect to surface manually. When one of the vertical springs compresses its adjacent horizontal springs will pull on its adjacent vertical springs causing a rippling effect. The vertical springs have very a very low stiffness and damping so that they oscillate easier and for longer. The horizontal springs have a very high stiffness as they influence the magnitude of the ripple. When a rock is dropped at the point of it hitting the surface the two vertical springs it lands inbetween have a downwards force applied to them, and the physics does the rest. You can achieve a cleaner effect by having only vertical springs and manually changing the vertical velocity component of neighbouring springs based on the delta height. This produced less lateral movement, but I think looks less interesting than having horizontal springs. It's a matter of preference. As you can see from the 'debug' version of the demo the surface is just a collection of points, which when the area underneath is filed creates a row of trapeziums rather than a nice fluid surface. To an extent you can increase the number of vertical springs, as a smaller step will mean a smoother curve, but the simulation starts to look much worse as the number of springs is increased, not to mention the increase in resource usage. A simpler solution is to interpolate between the points to create a smooth curve. I used the Catmull-Rom spline method, which ensures the curve goes through all the points (important for collisions with the surface). I'm interpolating with 8 steps between each control point, but you can change the to increase/decrease performance or decrease/increase smoothness without affecting the simulation.