Keep vectors exactly 15 distance apart

So I have a starting vector and I have a vector point with a box graphic that be dragged. Currently it can be dragged up,down, and outwards. I want to constrain it so that it is always 15 distance away as it is dragged around the start point vector. How would I achieve this?

There is a Vector3.Distance function you can use to check the distance between 2 vectors, you can stop the object from being dragged the moment if is 15 or more from the starting point. you will never stop it at exactly 15, but it will be close enough to fool the human eye

The general approach is:

  • get the relative vector from your starting / center position to your drag position
    v = P - S;
  • perform the constraint you want on v (see below)
  • get back the absolute vector by doing the reverse of #1:
    P = S + v;

There are different ways you could constrain such a relationship:

  • Always keep an exact distance of 15. This basically restricts the object to only move on a circular path around the center:
    v = v.normalized * 15;
  • Allow any position inside the specifed circle but no position outside the circle.
    v = Vector3.ClampMagnitude(v, 15);
  • Ensure at least a distance of 15 but allow any further position. This would keep the circular area around the center free. So this just ensures a minimum distance,
    if (v.sqrMagnitude < 15*15) v = v.normalized * 15;

So for example the first case would look something like this:

// always distance of 15 units
Vector3 v = dragPos - centerPos;
v = v.normalized * 15;
dragPos = centerPos + v;

Of course if your “dragPos” comes from a gameobject position you want to update it’s position as well.

ps: “ClampMagnitude” basically just does this:

if (v.sqrMagnitude > 15*15)
    v = v.normalized * 15;