Clamp transform position based on the distance

Hi guys.
I’m dragging an object with along the screen.
I would like to prevent the possibility to move the object out of the screen.
I’m saving the start position and checking the distance between the current and the start position of the object.
I’m using this bit of code:

float distance = Vector3.Distance(transform.position, startPosition);
if (distance > maxDistanceFromOrigin) {
   // TODO - clamp the position to avoid to go out from the limit.
}

but I can’t figure out how to clamp the position so it can’t go out of the limit distance.

I can’t just clamp the Vector3 values because before this operation, I use:

transform.Translate(Vector3.right * deltaX, Camera.Main.transform);
transform.Translate(Vector3.up * deltaY, Camera.Main.transform);

where the delta are the differences between the current and the previous mouse/touch positions.

Thank you. :slight_smile:

Calculate the new position using the delta and then put your Translate calls inside the if statements. This way you only update the position if it falls within your boundary.

Sometime the simplest solution is the best. Thank you very much man, I don’t know how come that I’ve not thought about that.

Thanks again :slight_smile: