Fixing object at Ray`s origin

I have a sphere which rotates around the box.
The sphere looks at the box with LookAt and casts a Ray with Raycast, transform.forward.
The lenght of the ray is 10 meters.
What I want to do is that when I drag the sphere from the box further than 10 meters (i.e. my ray no longer hits the box) the sphere should move no further (however I shall still be able to rotate it around boxes “orbit”).

As I understand what I need to do is find the coordinates of ray`s origin while the ray is about to leave the box and give the sphere the coordinates of rays origin.

How should I do it? Or maybe there`s an easier way?

Here is my code if any:

void OnMouseDrag () {
	Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	transform.position = new Vector3(ray.GetPoint (9).x, transform.position.y, ray.GetPoint (9).z);// I`m moving the sphere with the mouse;
	Physics.Raycast (transform.position, transform.forward, 10);
	Debug.DrawRay(transform.position, transform.forward * 10, Color.red);

If I got your explanation right, I have more than one way in mind,

  1. If your box has a collider on it you can do a collision check of your ray and your box collider. And have the return bool value drive the capability of dragging your box. (Although I would recommend using a sphere collider. It makes a lot more sense given your example, and keep the radius of your sphere in mind).

  2. Im not sure if your ray cast is necessary in any way but if it isn’t you can simply get the distance between the two Vector3(your sphere and your box) and if its larger than 10 disable drag.

    float distance = Vector3.Distance(sphere.transform.position,box.transform.position);
    float max_Distance = 10.0f;

    if (distance > max_Distance)
    {
    }