There is a similar function for Vectors: Vector2.ClampMagnitude
and Vector3.ClampMagnitude
You can only specify a maximum length, so you have to take care of the minimum yourself. The problem with the minimum value is, that the function would not know what to do if the vector has a length of 0
. In which direction should the vector point to achieve the minimum length?
Limit input to a circle
If you only want to limit the movement to a circle, you don't need a minimum value. Instead define the center as (2,2)
and limit the movement to a radius of 2
.
Vector2 center = new Vector2(2f, 2f);
Vector2 moveBy = new Vector(4f, 7f); // set this to whatever your input is
moveBy = Vector2.ClampMagnitude(moveBy, 2f);
Vector2 newPosition = center + moveBy;
newPosition
will be inside a circle with a radius of 2
around your center at (2,2)
Limit given position to a circle
If you want to clamp a given position to a circle, you can slightly modify the version above. It's like putting the object on a leash and pull it back when it leaves the circle.
Vector2 center = new Vector2(2f, 2f);
Vector2 position = new Vector2(6f, 5f); // outside your desired circle
Vector2 offset = position - center;
Vector2.ClampMagnitude(offset, 2f);
position = center + offset;