Using WaterSearchParameters and WaterSearchResults to get distance from water


I was trying to find the distance of a point from the water surface in Unity HDRP and I stumbled upon this method from one of the forums:

public float CalculateHeightFromWater(Vector3 v)
    if (surface != null)
        // Build the search parameters
        searchParameters.startPositionWS = searchResult.candidateLocationWS;
        searchParameters.targetPositionWS = v.y;
        searchParameters.error = 0.01f;
        searchParameters.maxIterations = 8;

        // Do the search
        if (surface.ProjectPointOnWaterSurface(searchParameters, out searchResult))
            Debug.Log("Water height: " + searchResult.projectedPositionWS.y);
            Debug.Log("point y value: " + v.y);
            return v.y - searchResult.projectedPositionWS.y;
    return float.NaN;

However, I am not really sure how it works, especially .error and .maxIterations. After going through the documentation I got some idea as to what these fields (like startPositionWS and targetPositionWS, etc.) do but I still don’t understand how they fit into a context like this.

Moreover, when using this to calculate the distance of a vertex on a cube from the water surface, I get NaN for the height and I was trying to understand how these fields work exactly for an example scenario so that I am able to debug the issue.

Could someone please explain how these fields work?


You can let the searching parameters as this for precision or mitigate them. surface is the water here.

Everything happen in the surface.ProjectPointOnWaterSurface() method, this method is working like a usual Raycast and relevant to get a lot of Data from the Water simulation, as this method working as boolean, so we encapsulate in an if(), so the following result is accessible within the success of the “search”, note this method output (out) a searchresult which, as a raycast method, so you can definitively get the float result using this method like:

float HeightFromWater = CalculateHeightFromWater(v); 

(v being the tranform.positon Vector3 of your cube)

Another note, this function is a float, so in the end, you have the height!