Limitation on drag float value?

Hello, im trying to limit float values based off a drag starting from “minforce” to “maxforce”. But this code is getting the exact value of the drag that can be too much force or too little force. help is needed >.<

public Rigidbody2D rb;
Vector3 startpos, dragpos, endpos, dir;
public float minforce, maxforce;

void Update()
{
     if (Input.touchCount > 0)
    {
            touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {
                  Vector3 mousePosition = Input.mousePosition;
                  startpos = Camera.main.ScreenToWorldPoint(mousePosition);
                  startpos.z = 0;
            }

        if (touch.phase == TouchPhase.Moved)
        {
                Vector3 mousePosition = Input.mousePosition;
                dragpos = Camera.main.ScreenToWorldPoint(mousePosition);
                dragpos.z = 0;
        }
    
        if (touch.phase == TouchPhase.Ended)
        {
                endpos = Camera.main.ScreenToWorldPoint(touch.position);
                dir = startpos - endpos;
                Vector2 clamp = Vector2.ClampMagnitude(dir, maxforce) * minforce;
                rb.AddForce(clamp, ForceMode2D.Impulse);
        }
    }
}

Well, this line does not really keep the force anywhere between min and max:

Vector2 clamp = Vector2.ClampMagnitude(dir, maxforce) * minforce;

Your “dir” could have a length that is close to zero (or actually zero) in which case multiplying by minforce won’t get a vector with min force. For example if minforce is 20 and the actual length of the vector is “0.1” you get a force of 2 ( == 0.1 * 20 ).

Furthermore if the dir is really large, you clamp it to maxforce, but at the end you multiply by minforce. So if minforce is 20 and max force 300 and dir has a length of 500, the 500 will be clamped to 300 but since you multiply the result by minforce you would get an effective maxforce of 6000.

If you want to clamp the vector between min and max, you just want to split up the length of the vector from the direction, clamp the length and rescale the vector.

float length = dir.magnitude;
if (length < minforce)
    dir *= (minforce / length);
else if (length > maxforce)
    dir *=  (maxforce / length);

This will keep the length of dir between minforce and maxforce