Search code examples
c#unity-game-engineclampmagnitudevector2

How would you Clamp the relative position of an object?(Unity)


How would I clamp the magnitude of a relative position and convert to world coordinates? i.e. (this.pos - other.pos).clampMag(3f).toWorldCoor(); of course this doesn't exist, but how would I do this kind of thing?


Solution

  • Are you familiar with Vector3.ClampMagnitude and Transform.TransformPoint? If not I believe you could simply use:

    Vector3 localClamped = Vector3.ClampMagnitude(yourLocalVector, maxLength);
    Vector3 worldPos = someTransform.TransformPoint(localClamped);
    

    If you don't have a local transform you are working with, you can take your localClamped Vector3 and add whatever offset Vector3 you are working with.

    Vector3 worldPos = localClamped + offset;