Restrict/clamp the position of a player relative to the other player?

How do I restrict/clamp the position of a player relative to the other player?
So when the player is more than 6 studs away, they should be brought back.

Code so far:

        local compCF = companion.Character.PrimaryPart.CFrame
        local relativeCF = char.PrimaryPart.CFrame:ToObjectSpace(compCF)

        local newX = math.clamp(relativeCF.X, -6, 6)
        local newY = math.clamp(relativeCF.Y, -6, 6)
        local newZ = math.clamp(relativeCF.Z, -6, 6)

        local newPos = compCF.Position + Vector3.new(newX, newY, newZ)
        char.PrimaryPart.Position = newPos

The code gives this result:
https://gyazo.com/0dd287e49a0cfeb748c4ef1312b0bc3e
Which is restricting it to 6 studs, but makes it move weirdly around the player instead.

4 Likes

I would go from a different approach and use (Vector3 - Vector3).magnitude and then make the character move in the direction of the other until they’re 6 studs away.