How can I make the transform to avoid moving inside the limited range ?

The script is attached to the transform that follow/chase/catchup the target.

I’m using in two place with Vector3.MoveTowards
The reason for using it in two places is that the place in the else make the rotation of the transform when the target is rotating much more smooth. If I remove the Vector3.MoveTowards from the else part then when the target make sharp rotations the transform will stop for a millisecond even more and then rotate and then will move.

So using both places the Vector3.MoveTowards is making it follow smooth the target.
The problem is now that if the transform is in the range meaning the distance is less then 1.5 and then I’m moving the target(my player) very small distance one step moving then the transform will move too and so on after twice or so the transform is touching the target. but I want that it will keep the distance of 1.5 and that it will start moving only if the target have been moved more then 1.5 and to keep following in this distance.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Text text;
    public Text text1;
    public float lookAtRotationSpeed;
    public float moveSpeed;

    private float minMoveSpeed = 0f;
    private Vector3 originPos;

    // Start is called before the first frame update
    void Start()
    {
        originPos = targetToFollow.position;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        var distance = Vector3.Distance(transform.position, targetToFollow.position);

        text.text = "Transform Distance From Target " + distance.ToString();

        float ms = moveSpeed;

        if (distance > 5f)
        {
            ms = moveSpeed + 0.5f;
        }
        else if (distance < 1.5f)
        {
            ms = Mathf.Max(minMoveSpeed, ms - 0.3f);
        }
        else
        {
                transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);
        }

        if(distance < 0.5f && originPos == targetToFollow.position)
        {
            ms = 0f;
        }

        transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);

        originPos = targetToFollow.position;
    }
}

I would suggest separating the logic from the execution. Determine if you should move first, taking everything into consideration and set your variabled, then have one final check to move or not move.

2 Likes