How can I set up a 2D circular boundary in Unity?


I wanted to create a virtual analogue stick on Unity. enter image description here

I figured a very simple, 2 part method setting up a tether to the middle of a doughnut-container and a boundary would work. While the tether was quickly solved just by using Vector2.MoveTowards, the boundaries would be much harder to solve.

I initially tried to create a 2D circle collider around the doughnut-container but I didn’t know how to reverse its collisions to keep the cursor inside. Later, I tried to set up a square shaped boundary by setting up the limits of the x and y coordinates the cursor cannot exceed (these limits were also made according to the doughnut-container). Thus was done with multiple if statements:

 if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}  if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}  if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}  if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;} 

However, when testing the code out, the cursor still exceeded the boundaries given:

enter image description here

Minimum reproducible code for the cursor:

public class menuScript : MonoBehaviour {     public float speed;     public Vector2 originPoint;     private Vector2 currentPoint;     // Start is called before the first frame update     void Start()     {         Vector2 originPoint = transform.position;     }      // Update is called once per frame     void Update()     {         currentPoint = transform.position;         float step = 50 * Time.deltaTime;         float vertical = Input.GetAxis("Vertical") * Time.deltaTime * speed;         float horizontal = Input.GetAxis("Horizontal") * Time.deltaTime * speed;          if (horizontal != 0 || vertical != 0)         {         transform.Translate(horizontal, vertical, 0);         if (currentPoint.y >= 2.7f){currentPoint.y = 2.7f;}         if (currentPoint.x >= 2.5f){currentPoint.x = 2.5f;}         if (currentPoint.y <= -2.7f){currentPoint.y = -2.7f;}         if (currentPoint.x <= -2.5f){currentPoint.x = -2.5f;}         }         else         {             transform.position = Vector2.MoveTowards(transform.position, originPoint, step);         }              } }