Start and stopping animation using a Raycast and distance

Hi

Problem Statement : How do I trigger the stop animation command when my player has reached the destination.

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                MoveToCursor();

            }
        }

       private void MoveToCursor()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
            RaycastHit hit;
            bool hasHit = Physics.Raycast(ray, out hit);
            var hitPoint = hit.point;
            hitPoint.z = 0;
            float x = 0.3f;
            var playerPosition = transform.position;
            playerPosition.z = 0;
            var distance = Vector3.Distance(hitPoint,playerPosition);
       
            Debug.Log($"Distance: {distance}", this);

            if(hasHit)
            {
                GetComponent<NavMeshAgent>().destination = hit.point;
                unitAnimator.SetBool("IsWalking", true);
                 

            }
            

        }

So I need to creation a condition where I can check that the distance has been reached and run

unitAnimator.SetBool(“IsWalking”, false);

But my brain is not getting out of gear on this one

First off, always cache your component calls, as this code is extremely un-performant, when being called during runtime:

GetComponent<NavMeshAgent>().destination = hit.point;

Second, setup your function to only use the raycast to get the (hitPoint)position, so it only needs to run once(along with any other variables you need in one frame of logic).

Then have it set in Update the value for your distance:

var playerPosition = transform.position;
playerPosition.z = 0;
var distance = Vector3.Distance(playerPosition, hitPoint);

Along with a check:

if (distance < 0.1f) // more or less if needed
{
   isWalking = false;
}

If you are unsure what caching is, I suggest you research into it. It will save you a ton of problems later :slight_smile: