# 6. Buoyancy Hooks Tests and Pitfalls Part of [[Water and Stylized Surfaces]]. Back: [[5. Normals Reflections and Scene Color Refraction]]. > [!warning] Code not compiled in Unity > C# type-checked against Unity 6000.5.8f1 assemblies (see the hub). Buoyancy has not been play-tested. The wave-function smoke tests were type-checked but have not been run in the Test Runner. [[Physics 3D]] already covers Rigidbodies, forces, and interpolation. This part only adds "sample the same waves the shader uses, then push." ## 6.1 Probe buoyancy A single point at the object's origin will not tilt. Four or more probes (corners of a crate, keel points of a boat) let uneven heights produce torque when you apply force **at the probe position**. `Runtime/BuoyantBody.cs`: ```csharp using UnityEngine; namespace WaterAndStylizedSurfaces { [RequireComponent(typeof(Rigidbody))] public sealed class BuoyantBody : MonoBehaviour { [SerializeField] WaterSurface surface; [SerializeField] Transform[] probes; [SerializeField] float density = 0.75f; [SerializeField] float probeRadius = 0.25f; [SerializeField] float linearDragInWater = 1.5f; [SerializeField] float angularDragInWater = 1.0f; [SerializeField] float gravityMultiplier = 1f; Rigidbody _body; float _cachedAngularDrag; void Awake() { _body = GetComponent<Rigidbody>(); _cachedAngularDrag = _body.angularDamping; } void FixedUpdate() { if (surface == null || probes == null || probes.Length == 0) return; float waterDragApplied = 0f; Vector3 gravity = Physics.gravity * gravityMultiplier; // Unity already applies gravity to the Rigidbody if useGravity is on. // This script assumes useGravity stays on, and only adds buoyancy and extra drag. for (int i = 0; i < probes.Length; i++) { if (probes[i] == null) continue; Vector3 pos = probes[i].position; float waterY = surface.Height(pos); float depth = waterY - pos.y + probeRadius; if (depth <= 0f) continue; float submerged = Mathf.Clamp01(depth / Mathf.Max(1e-4f, probeRadius * 2f)); // Archimedes, grossly: upward force proportional to submerged fraction, // scaled so a density < 1 floats, density > 1 sinks. float displacement = submerged / Mathf.Max(0.05f, density); Vector3 force = -gravity * (_body.mass / probes.Length) * displacement; _body.AddForceAtPosition(force, pos, ForceMode.Force); Vector3 pointVel = _body.GetPointVelocity(pos); _body.AddForceAtPosition(-pointVel * linearDragInWater * submerged, pos, ForceMode.Force); waterDragApplied += submerged; } float avg = waterDragApplied / probes.Length; _body.angularDamping = Mathf.Lerp(_cachedAngularDrag, angularDragInWater, avg); } void OnDisable() { if (_body != null) _body.angularDamping = _cachedAngularDrag; } } } ``` Notes, all tied to official physics APIs: - `Rigidbody.AddForceAtPosition` is the torque path. `ForceMode.Force` is acceleration-time-mass over `FixedUpdate`. - `Rigidbody.GetPointVelocity` is the official point-velocity query. - **`angularDamping`** is the Unity 6 / 6000.x name that replaced the old `Rigidbody.angularDrag` property. This listing uses `angularDamping`. If you backport the script, check the Scripting API for your exact Editor; the old name is obsolete in 6000.5. - `Physics.gravity` is the project gravity vector. - `density` is a teaching knob, not a fluid sim: values below 1 float, above 1 sink, when probes are placed reasonably around the body. Scene setup: 1. `WaterSurface` on the water (part 4), waves matching the material. 2. A crate with a Rigidbody, convex collider, four child empties at its corners, and `BuoyantBody` assigned those probes and the surface. 3. Drop the crate from a small height onto the pond. It should bob and settle. If it sinks like a stone, raise `probeRadius` (so a flush-to-surface probe still counts as partly submerged) or lower `density`. If it explodes upward, lower the displacement or the number of overlapping probes. This is a hook, not a boat sim: there is no hydrodynamic lift, no planing, no buoyancy mesh volume. ## 6.2 Smoke test of the shared function These assertions do not need a scene. They pin the math the shader is supposed to copy. Put them in an Edit Mode test assembly if you use [[Unity Test Framework]], or run them as a tiny Editor menu. The exact NUnit form is optional; the conditions are not. ```csharp using NUnit.Framework; using UnityEngine; using WaterAndStylizedSurfaces; public sealed class WaterWavesTests { [Test] public void FlatWaves_HaveZeroHeight_AndUpNormal() { var waves = new[] { WaterWave.Sine(Vector2.right, 0f, 10f, 1f) }; Assert.AreEqual(0f, WaterWaves.Height(Vector2.zero, 0f, waves)); Assert.AreEqual(Vector3.up, WaterWaves.Normal(Vector2.zero, 0f, waves)); } [Test] public void SineWave_AtQuarterWavelength_IsPlusAmplitude() { var wave = WaterWave.Sine(Vector2.right, 2f, 8f, 0f); // speed 0, phase = k * x, k = 2π/8, at x = 2 (L/4), sin(π/2) = 1 float y = WaterWaves.Height(new Vector2(2f, 0f), 0f, new[] { wave }); Assert.That(y, Is.EqualTo(2f).Within(1e-5f)); } [Test] public void Displace_WithZeroSteepness_MovesOnlyY() { var wave = WaterWave.Sine(Vector2.right, 1f, 8f, 0f); var rest = new Vector3(2f, 5f, 0f); var displaced = WaterWaves.Displace(rest, 0f, new[] { wave }); Assert.That(displaced.x, Is.EqualTo(2f).Within(1e-5f)); Assert.That(displaced.z, Is.EqualTo(0f).Within(1e-5f)); Assert.That(displaced.y, Is.EqualTo(6f).Within(1e-5f)); } [Test] public void Gerstner_WithSteepness_MovesHorizontally() { var wave = new WaterWave { direction = Vector2.right, amplitude = 1f, wavelength = 8f, speed = 0f, steepness = 1f }; var rest = new Vector3(0f, 0f, 0f); // phase 0, sin 0, cos 1, so Y=0, X += q*A var displaced = WaterWaves.Displace(rest, 0f, new[] { wave }); Assert.That(displaced.x, Is.EqualTo(1f).Within(1e-5f)); Assert.That(displaced.y, Is.EqualTo(0f).Within(1e-5f)); } } ``` The last test is a reminder: at phase 0 a steep Gerstner wave has **no vertical displacement** and a **horizontal** push. A crate sampled only with `Height` at that XZ still sees 0, which is consistent with the vertex Y, even though the mesh particle that started there has slid sideways. ## 6.3 Pitfalls | Symptom | Likely cause | Fix | |---|---|---| | Depth fade is a constant mid-grey / 0.5 look | Depth Texture off on the **active** URP asset | Part 1: enable it on the Quality level you actually run | | Scene Color is black or stale | Opaque Texture off, or the graph is still Opaque | Surface Type Transparent; enable Opaque Texture | | Foam / fade outlines a character | The character writes the depth texture | Accept it, or a custom depth copy ([[Custom URP Renderer Features]]) — not in this series | | Fade halo grows when the camera goes low | Eye difference is along the view ray | Expected with Scene Depth Difference Eye; not a vertical depth | | Waves look like a flat plate, lighting-wise | Vertex move without a matching normal | Part 5: world-space wave normal into the Lit block | | Crate does not follow visible crests | Material wave numbers ≠ `WaterSurface` waves, or C# uses `unscaledTime` | Push the same parameters; use `Time.time` to match the Time node (`_Time.y`) | | Crate clips a Gerstner crest | Eulerian sample vs Lagrangian displacement | Leave steepness at 0, or accept the approximation in part 4 | | Plane tears / folds | Steepness summed across waves is too high, or the mesh is too coarse | Lower steepness; subdivide (part 1) | | Buoyancy explodes | Too much displacement, `FixedUpdate` + huge `density` inverse, probes bunched | Lower forces; spread probes; keep `useGravity` on and only add buoyancy | | `angularDrag` does not compile | Property renamed in Unity 6 | Use `angularDamping` (this listing) | | Refraction smears silhouettes | `RefractionStrength` too high, or a downsampled opaque texture | Lower the strength; skip refraction on cheap Quality levels | | Water missing in a second camera | That camera or its Quality asset disabled the textures | Per-camera and per-asset Depth / Opaque Texture overrides | ## 6.4 What this series did not cover - Underwater camera, caustics, or volumetric scattering. - Flow maps and rivers with a current (you can add a constant XZ velocity to `BuoyantBody` once you have one). - GPU tessellation or a projected grid for an ocean to the horizon. - A custom Renderer Feature for a scenery-only depth pre-pass. - HDRP water, or the official Unity Water package if one is present in a later Editor — this series is Shader Graph on URP 17.5.0 only. Back to the hub: [[Water and Stylized Surfaces]].