Using Collider.ClosestPoint throws warning when using Terrain Colliders.

Hello,

I am currently having a problem where I am trying to get the closest point on a Terrain Collider.

Code in question:

     Vector3 directionToObstacle;
                //Get the direction to the obstacle based on how close it is to the agent on the closest point
                if (obstacleCollider is TerrainCollider)
                {
                    Debug.Log("is terrain");
                    var position = _transform.position;
                    directionToObstacle =GameManager.instance.terrainCollider.ClosestPoint(position) -
                        position;
                }else
                {
                    var position = _transform.position;
                    directionToObstacle= obstacleCollider.ClosestPoint(position) - position;
                }

When using this, terrainCollider.ClosestPoint() throws a warning stating that this can’t be used. While that’s fine, upon looking into documentation, it seems to be supported? I know Terrain Collider inherits Collider, which is why they can’t block it off.

Is there an equivalent for Terrains? Or am I going to have to make my own solution?

Thanks!

Of course they could: just override the method and have it throw the above exception!

I’m not privy to the Unity engine but if I had to guess it is because Terrain “vertices” are extremely ephemeral and produced just “on the fly,” and tesselated to precisely the level of detail needed given the distance from camera and complexity of the ground.

To see what I mean, enable wireframe mode and go look at your Terrain.

For a solution, perhaps just raycast down and hit the terrain? Or raycast a few directions around you and see which hit is closest?

1 Like

For those still interested, I had the same issue and I used
ClosestPointOnBounds() instead of ClosestPoint()

For me it had the same effect without the warning :slight_smile: