Limit the position of the object, but still keep following the touch? How to use ClampMagnitude properly?

How do I limit/clamp the position of an object that’s following the touch, but still be able to follow the touch?

I want it to be like this one:

alt text

I also tried magnitude.clamp but it just won’t work for some reason. Maybe I’m doing something wrong with it? Nothing happens when I insert the magnitude.clamp code. With or without it, the results are the same.

I’m also using a 2nd camera on Orthographic View. Maybe that has something to do with it? The only limiter I’m using right now are the colliders, but it doesn’t follow the touch anymore once the touch is outside the collider, and I don’t want that to happen.

Here’s the code I’m currently using:

if (Input.touchCount > 0) 
	Ray ray = camera2.ScreenPointToRay(theTouch[0].position);
	//When the touch is out of the "border", this object completely stops following the touch
	//I want it to just limit the position of this object, but still keep following the touch
	//Where it can still detect where my touches are, and then try to follow it, but it can't go outside the border	
	if(Physics.Raycast(ray, out hit) && hit.collider.tag == "border")
			Touch touch = Input.GetTouch(0);
			if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) 
			//Finds the position of the touch	
			touchPosition = camera2.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));          
			//Follows the touch
			transform.position = Vector3.Lerp(transform.position, touchPosition, Time.deltaTime * 10);

Thanks! I’ve tried Google and searching here on Unity Answers but found none unfortunately

Unless you’re very sure of what you’re doing, you’re using Lerp incorrectly.

Assuming 30fps, this Lerp call gives you a point about 33% between pos1 and pos2:

Vector3 v = Vector3.Lerp(pos1, pos2, Time.deltaTime * 10);

This MoveTowards call gives you a point that moves from pos1 toward pos2 at about 10 meters per second:

Vector3 v = Vector3.MoveTowards(pos1, pos2, Time.deltaTime * 10);

Finally, I don’t see any ClampMagnitude call in your code. If you’re trying to clamp within a sphere, that should do the trick. If one axis of the vector is guaranteed to be zero, then it’ll clamp on a circle.

This would clamp within 10 units, for example:

Vector3 v2 = Vector3.ClampMagnitude(v, 10f);