Minimum clampmagnitude help

So I’ve been working on a script that uses Vector2.ClamMagnitude to keep an aiming reticle within a certain area. I’m look for an efficient way to also have a minimum radius or a way to lock the reticle on the maximum radius. This is the code I’ve got:

public class Weapons : MonoBehaviour {

    public GameObject playerObject;
    public Transform cursor;
    public float radius;

    private Vector2 mousePos;
    private Vector2 centerPoint;
   


    void Update()
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        centerPoint = playerObject.transform.position;


        if (Input.GetMouseButton(1))
        {
            cursor.GetComponent<SpriteRenderer>().enabled = true;
            Vector2 newPos = mousePos;
            Vector2 offset = newPos - centerPoint;
            cursor.position = centerPoint + Vector2.ClampMagnitude(offset, radius);
        }
        else
        {
            cursor.GetComponent<SpriteRenderer>().enabled = false;
        }
       
    } 
}

So yea the reticle is currently able to move freely within the boundaries of the radius but I’d like to find a way to either force it to stay at the edge or have a minimum radius feature. How should I go about achieving this? :slight_smile:

One way you can clamp it to the edge is to turn it into a normalized direction vector.

For instance, where you have this code:

You can then normalize ‘offset’ so it has a vector length of 1

Vector2 normalizedOffset = offset.normalized;

You can also get the length at that point:

float offsetLength = offset.magnitude;

Now you can either clamp it to a fixed radius by doing something like this:

float fixedRadius = 20.0f;
cursor.position = centerPoint + ( normalizedOffset * fixedRadius );

Or clamp the radius first:

float clampedRadius = Mathf.Clamp( offsetLength , 5.0f , 20.0f );
cursor.position = centerPoint + ( normalizedOffset * clampedRadius );

Thanks a lot man! You really helped me out :slight_smile: