Prevent a GameObject from leaving a particular region

I’m trying to prevent a GameObject from leaving a particular region. Now the hard part is that the region doesn’t have to be rectangular shaped so what I’ve been doing so far–clamping the x & y values of the GameObject’s destination to the min/max bounds of the shape–will not work. I need a to find a way to constrain the GameObject to the shape defined in the class. The GameObject is also a kinematic rigidbody so that make things a bit more difficult.

This is some of the code I have so far (WIP):

``````public class Prisoner2D : Component
{
[SerializeField] private Movement _movement;
[SerializeField] private Collider2D _prison;

private Bounds _bounds;

private void Start()
{
if (_prison != null)
{
_bounds = _prison.bounds;
}
}

public void SetPrison(Collider2D prison)
{
_prison = prison;
_bounds = prison.bounds;
}

public void MoveTo(Vector2 position)
{
Vector2 min;
Vector2 max;

if (!_prison.gameObject.isStatic)
{
var bounds = _prison.bounds;
min = bounds.min;
max = bounds.max;
}
else
{
min = _bounds.min;
max = _bounds.max;
}

float x = Mathf.Clamp(position.x, min.x, max.x);
float y = Mathf.Clamp(position.y, min.y, max.y);
var destination = new Vector2(x, y);
_movement.MoveTo(destination);
}

public void MoveTo(Vector3 position)
{
Vector2 position2D = position;
MoveTo(position2D);
}
}
``````

Simple approach is to use a different collision layer - Unity - Manual: Layer-based collision detection