Clamping a value between two radiuses
I'd like to clamp the transform.localPosition of an object between two values to keep the object in the space between the inner and outer circles. Using colliders to use this is unfortunately not the solution I'm seeking, I only put them here for illustration purposes (see attached gif)
This is what I have so far: (_newPos is received from my UIPointer script which is just calculated from the screenposition of the cursor (the "O" sprite in the gif) .
Vector3 _newPosition = new Vector3(_newPos.x, _newPos.y, 0);
var initialPos = transform.localPosition;
var allowedPos = _newPosition - initialPos;
allowedPos = (Vector3.ClampMagnitude(allowedPos, captureDistance));
transform.localPosition = Vector3.MoveTowards(transform.localPosition, Vector3.ClampMagnitude(initialPos + allowedPos, captureDistance), maxDistanceDelta);
What this achieves is clamping within the "outer circle" essentially as in the GIF.
In my example, captureDistance is 100 (outer circle), and I'd like to disallow the object from entering below 40 (so clamp it between a circle with a radius of 40, and another with a radius of 100).
How would I go about this? Thank you
Answer by theembracedone · Dec 13, 2021 at 07:30 PM
Solution, suggested by a user on a Discord server:
Vector3 _newPosition = new Vector3(_newPos.x, _newPos.y, 0);
var _allowedPos = _newPosition - transform.localPosition;
_allowedPos = Vector3.MoveTowards(transform.localPosition, _allowedPos, maxDistanceDelta);
transform.localPosition = _allowedPos.normalized * Mathf.Clamp(_allowedPos.magnitude, captureDistanceMin, captureDistanceMax);
captureDistanceMin = inner circle's radius
captureDistanceMax = outer circle's radius