how can i limit position between 2 object ??

hello everyone, i am new in unity, i just want make my object[2] can move around object[1], but not to far from object[1], it’s just like pict 1, I have searched many solutions on the internet, but not many teach me how to limit position, is there anyone who can teach me.
Thanks, :smiley:
109074-degrees-360-2.jpg

Here is a very basic joystick script.

  1. Create two images with a circle shaped sprite.

  2. Make the 2nd a child of the 1st one

  3. Attach the following script to the child

  4. Drag & drop the 1st circle (parent) into the parent field

  5. Drag & drop the 2nd circle (child) into the rectTransform field

    using UnityEngine;
    using UnityEngine.EventSystems;
    
    public class Joystick : MonoBehaviour, IBeginDragHandler, IDragHandler
    {
        public RectTransform parent;
        public RectTransform rectTransform;
        private float radius;
        Vector2 offset;
    
        private void Start()
        {
            radius = rectTransform.sizeDelta.x;
        }
    
        public void OnBeginDrag( PointerEventData eventData )
        {
            Vector2 pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle( parent, Input.mousePosition, eventData.pressEventCamera, out pos );
            offset = rectTransform.anchoredPosition - pos;
        }
    
        public void OnDrag( PointerEventData eventData )
        {
            Vector2 pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle( parent, Input.mousePosition, eventData.pressEventCamera, out pos );
            Vector2 desiredPosition = pos + offset;
    
            if( desiredPosition.sqrMagnitude > radius * radius )
            {
                desiredPosition = desiredPosition.normalized * radius;
            }
            rectTransform.anchoredPosition = desiredPosition;
        }
    }
    

#INITIAL ANSWER

Your question is not very clear, any existing code would help.

But basically, you can limit the distance between Object2 and Object1 like this :

public void LimitPosition( GameObject gameobject2, GameObject gameobject1, float maxDistance )
{
    Vector3 position2 = gameobject2.transform.position;
    Vector3 position1 = gameobject1.transform.position;
    Vector3 direction = position2 - position1;
    float sqrDistance = direction.sqrMagnitude;
    if ( sqrDistance > maxDistance * maxDistance )
    {
        gameobject2.transform.position = direction.normalized * maxDistance + position1;
    }
}