Monday, August 15, 2016

Creating Dynamic 2D Water Effects in Unity_part 2 (end)

Creating Our Collisions

Now we want our collider too:
  1. colliders[i] = new GameObject();
  2. colliders[i].name = "Trigger";
  3. colliders[i].AddComponent<BoxCollider2D>();
  4. colliders[i].transform.parent = transform;
  5. colliders[i].transform.position = new Vector3(Left + Width * (i + 0.5f) / edgecount, Top - 0.5f, 0);
  6. colliders[i].transform.localScale = new Vector3(Width / edgecount, 1, 1);
  7. colliders[i].GetComponent<BoxCollider2D>().isTrigger = true;
  8. colliders[i].AddComponent<WaterDetector>();
Here, we're making box colliders, giving them a name so they're a bit tidier in the scene, and making them each children of the water manager again. We set their position to be halfway between the nodes, set their size, and add a WaterDetector class to them.

Now that we have our mesh, we need a function to update it as the water moves:
  1. void UpdateMeshes()
  2.     {
  3.         for (int i = 0; i < meshes.Length; i++)
  4.         {
  5.  
  6.             Vector3[] Vertices = new Vector3[4];
  7.             Vertices[0] = new Vector3(xpositions[i], ypositions[i], z);
  8.             Vertices[1] = new Vector3(xpositions[i+1], ypositions[i+1], z);
  9.             Vertices[2] = new Vector3(xpositions[i], bottom, z);
  10.             Vertices[3] = new Vector3(xpositions[i+1], bottom, z);
  11.  
  12.             meshes[i].vertices = Vertices;
  13.         }
  14.     }
You might notice that this function just uses the code we wrote before. The only difference is that this time we don't have to set the tris and UVs, because these stay the same.

Our next task is to make the water itself work. We'll use FixedUpdate() to modify them all incrementally.
  1. void FixedUpdate()
  2. {
Implementing the Physics

First, we're going to combine Hooke's Law with the Euler method to find the new positions, accelerations and velocities.

So, Hooke's Law is \(F = kx\), where \(F\) is the force produced by a spring (remember, we're modelling the surface of the water as a row of springs), \(k\) is the spring constant, and \(x\) is the displacement. Our displacement is simply going to be the y-position of each node minus the base height of the nodes.

Next, we add a damping factor proportional to the velocity of the force to dampen the force.
  1. for (int i = 0; i < xpositions.Length ; i++)
  2.         {
  3.             float force = springconstant * (ypositions[i] - baseheight) + velocities[i]*damping ;
  4.             accelerations[i] = -force;
  5.             ypositions[i] += velocities[i];
  6.             velocities[i] += accelerations[i];
  7.             Body.SetPosition(i, new Vector3(xpositions[i], ypositions[i], z));
  8.         }
The Euler method is simple; we just add the acceleration to the velocity and the velocity to the position, every frame.

Note: I just assumed the mass of each node was 1 here, but you'll want to use:
  1. accelerations[i] = -force/mass;
if you want a different mass for your nodes.

Tip: For precise physics, we would use Verlet integration, but because we're adding damping, we can only use the Euler method, which is a lot quicker to calculate. Generally, though, the Euler method will exponentially introduce kinetic energy from nowhere into your physics system, so don't use it for anything precise.

Now we're going to create wave propagation. The following code is adapted from Michael Hoffman's tutorial.
  1. float[] leftDeltas = new float[xpositions.Length];
  2. float[] rightDeltas = new float[xpositions.Length];
Here, we create two arrays. For each node, we're going to check the height of the previous node against the height of the current node and put the difference into leftDeltas.

Then, we'll check the height of the subsequent node against the height of the node we're checking, and put that difference into rightDeltas. (We'll also multiply all values by a spread constant).
  1. for (int j = 0; j < 8; j++)
  2. {
  3.     for (int i = 0; i < xpositions.Length; i++)
  4.     {
  5.         if (i > 0)
  6.         {
  7.             leftDeltas[i] = spread * (ypositions[i] - ypositions[i-1]);
  8.             velocities[i - 1] += leftDeltas[i];
  9.         }
  10.         if (i < xpositions.Length - 1)
  11.         {
  12.             rightDeltas[i] = spread * (ypositions[i] - ypositions[i + 1]);
  13.             velocities[i + 1] += rightDeltas[i];
  14.         }
  15.     }
  16. }
We can change the velocities based on the height difference immediately, but we should only store the differences in positions at this point. If we changed the position of the first node straight off the bat, by the time we looked at the second node, the first node will have already moved, so that'll ruin all our calculations.
  1. for (int i = 0; i < xpositions.Length; i++)
  2. {
  3.     if (i > 0) 
  4.     {
  5.         ypositions[i-1] += leftDeltas[i];
  6.     }
  7.     if (i < xpositions.Length - 1) 
  8.     {
  9.         ypositions[i + 1] += rightDeltas[i];
  10.     }
  11. }
So once we've collected all our height data, we can apply it at the end. We can't look to the right of the node at the far right, or to the left of the node at the far left, hence the conditions i > 0 and i <  xpositions.Length - 1.

Also, note that we contained this whole code in a loop, and ran it eight times. This is because we want to run this process in small doses multiple times, rather than one large calculation, which would be a lot less fluid.

Adding Splashes

Now we have water that flows, and it shows. Next, we need to be able to disturb the water!

For this, let's add a function called Splash(), which will check the x-position of the splash, and the velocity of whatever is hitting it. It should be public so that we can call it from our colliders later.
  1. public void Splash(float xpos, float velocity)
  2. {
First, we need to make sure that the specified position is actually within the bounds of our water:
  1. if (xpos >= xpositions[0] && xpos <= xpositions[xpositions.Length-1])
  2. {
And then we'll change xpos so it gives us the position relative to the start of the body of water:
  1. xpos -= xpositions[0];
Next, we're going to find out which node it's touching. We can calculate that like this:
  1. int index = Mathf.RoundToInt((xpositions.Length-1)*(xpos / (xpositions[xpositions.Length-1] - xpositions[0])));
So, here's what going on here:
  1. We take the position of the splash relative to the position of the left edge of the water (xpos).
  2. We divide this by the position of the right edge relative to the position of the left edge of the water.
  3. This gives us a fraction that tells us where the splash is. For instance, a splash three-quarters of the way along the body of water would give a value of 0.75.
  4. We multiply this by the number of edges and round this number, which gives us the node our splash was closest to.
  1. velocities[index] = velocity;
Now we set the velocity of the object that hit our water to that node's velocity, so that it gets dragged down by the object.

Note: You could change this line to whatever suits you. For instance, you could add the velocity to its current velocity, or you could use momentum instead of velocity and divide by your node's mass.


Now we want to make a particle system that'll produce the splash. We defined that earlier; it's called "splash" (creatively enough). Be sure not to confuse it with Splash(). The one I'll be using is included in the source files.

First, we want to set the parameters of the splash to change with the velocity of the object.
  1. float lifetime = 0.93f + Mathf.Abs(velocity)*0.07f;
  2. splash.GetComponent<ParticleSystem>().startSpeed = 8+2*Mathf.Pow(Mathf.Abs(velocity),0.5f);
  3. splash.GetComponent<ParticleSystem>().startSpeed = 9 + 2 * Mathf.Pow(Mathf.Abs(velocity), 0.5f);
  4. splash.GetComponent<ParticleSystem>().startLifetime = lifetime;
Here, we've taken our particles, set their lifetime so they won't die shortly after they hit the surface of the water, and set their speed to be based on the square of their velocity (plus a constant, for small splashes).

You may be looking at that code and thinking, "Why has he set the startSpeed twice?", and you'd be right to wonder that. The problem is, we're using a particle system (Shuriken, provided with the project) that has its start speed set to "random between two constants". Unfortunately, we don't have much access over Shuriken by scripts, so to get that behaviour to work we have to set the value twice.

Now I'm going to add a line that you may or may not want to omit from your script:
  1. Vector3 position = new Vector3(xpositions[index],ypositions[index]-0.35f,5);
  2. Quaternion rotation = Quaternion.LookRotation(new Vector3(xpositions[Mathf.FloorToInt(xpositions.Length / 2)], baseheight + 8, 5) - position);
Shuriken particles won't be destroyed when they hit your objects, so if you want to make sure they aren't going to land in front of your objects, you can take two measures:
  1. Stick them in the background. (You can tell this by the z-position being 5).
  2. Tilt the particle system to always point towards the center of your body of water—this way, the particles won't splash onto the land.
The second line of code takes the midpoint of the positions, moves upwards a bit, and points the particle emitter towards it. I've included this behaviour in the demo. If you're using a really wide body of water, you probably don't want this behaviour. If your water is in a small pool inside a room, you may well want to use it. So, feel free to scrap that line about rotation.
  1.         GameObject splish = Instantiate(splash,position,rotation) as GameObject;
  2.         Destroy(splish, lifetime+0.3f);
  3.     }
  4. }
Now, we make our splash, and tell it to die a little after the particles are due to die. Why a little afterwards? Because our particle system sends out a few sequential bursts of particles, so even though the first batch only last till Time.time + lifetime, our final bursts will still be around a little after that.

Yes! We're finally done, right?

Collision Detection

Wrong! We need to detect our objects, or this was all for nothing!

Remember we added that script to all our colliders before? The one called WaterDetector?

Well we're going to make it now! We only want one function in it:
  1. void OnTriggerEnter2D(Collider2D Hit)
  2. {
Using OnTriggerEnter2D(), we can specify what happens whenever a 2D Rigid Body enters our body of water. If we pass a parameter of Collider2D we can find more information about that object.
  1. if (Hit.rigidbody2D != null)
  2. {
We only want objects that contain a rigidbody2D.
  1.       transform.parent.GetComponent<Water>().Splash(transform.position.x, Hit.rigidbody2D.velocity.y*Hit.rigidbody2D.mass / 40f);
  2.     }
  3. }
Now, all of our colliders are children of the water manager. So we just grab the Water component from their parent and call Splash(), from the position of the collider.

Remember again, I said you could either pass velocity or momentum, if you wanted it to be more physically accurate? Well here's where you have to pass the right one. If you multiply the object's y-velocity by its mass, you'll have its momentum. If you just want to use its velocity, get rid of the mass from that line.

Finally, you'll want to call SpawnWater() from somewhere. Let's do it at launch:
  1. void Start()
  2. {
  3.     SpawnWater(-10,20,0,-10);
  4. }
And now we're done! Now any rigidbody2D with a collider that hits the water will create a splash, and the waves will move correctly.


Bonus Exercise

As an extra bonus, I've added a few lines of code to the top of SpawnWater().
  1. gameObject.AddComponent<BoxCollider2D>();
  2. gameObject.GetComponent<BoxCollider2D>().center = new Vector2(Left + Width / 2, (Top + Bottom) / 2);
  3. gameObject.GetComponent<BoxCollider2D>().size = new Vector2(Width, Top - Bottom);
  4. gameObject.GetComponent<BoxCollider2D>().isTrigger = true;
These lines of code will add a box collider to the water itself. You can use this to make things float in your water, using what you've learnt.

You'll want to make a function called OnTriggerStay2D() which takes a parameter of Collider2D Hit. Then, you can use a modified version of the spring formula we used before that checks the mass of the object, and add a force or velocity to your rigidbody2D to make it float in the water.

Make a Splash

In this tutorial, we implemented a simple water simulation for use in 2D games with simple physics code and a line renderer, mesh renderers, triggers and particles. Perhaps you will add wavy bodies of fluid water as an obstacle to your next platformer, ready for your characters to dive into or carefully cross with floating stepping stones, or maybe you could use this in a sailing or windsurfing game, or even a game where you simply skip rocks across the water from a sunny beach. Good luck!
Written by Alex Rose

If you found this post interesting, follow and support us.
Suggest for you:

Make VR Games in Unity with C# - Cardboard, Gear VR, Oculus

Learn to Code by Making Games - The Complete Unity Developer

Make a Multiplayer Shooter in Unity

Unity 5 Host Your Game Server Online like a PRO

Start Learning Unity3d by Making 5 Games from Scratch

1 comment:

  1. The original tutorial
    https://gamedevelopment.tutsplus.com/tutorials/creating-dynamic-2d-water-effects-in-unity--gamedev-14143

    ReplyDelete