Different Stoping Distance Approach

Hi all!

In this lesson I used a different stopping method to make the player stop at a certain distance and I want to ask if it is a wrong approach or may result in a bug latter on.

    public class Mover : MonoBehaviour
    {
        Animator characterAnimator;
        NavMeshAgent entityNavmeshAgent;

        void Start()
        {
            characterAnimator = GetComponent<Animator>();
            entityNavmeshAgent = GetComponent<NavMeshAgent>();
        }

        void Update()
        {
            UpdateAnimator();
        }

        public void MoveTo(Vector3 destination, float distance)
        {
            entityNavmeshAgent.destination = destination;
            StopDistance(distance);
        }

        public void StopDistance(float distance)
        {
            entityNavmeshAgent.stoppingDistance = distance;
        }

        private void UpdateAnimator()
        {
            Vector3 velocity = entityNavmeshAgent.velocity;
            Vector3 localVelocity = transform.InverseTransformDirection(velocity);
            float speed = localVelocity.z;

            GetComponent<Animator>().SetFloat("forwardSpeed", speed);

        }
    }
    public class Fighter : MonoBehaviour
    {
        [SerializeField] float weaponRange = 2f;
        Transform target;
        private void Update()
        {
            if(target != null)
            {
                GetComponent<Mover>().MoveTo(target.position, weaponRange);
            }
        }
        public void Attack(CombatTarget combatTarget)
        {
            if(combatTarget != null)
            {
                target = combatTarget.transform;
            }
            
        }
    }

Let me know if my line of thinking is wrong in any way, I’m not a fully programmer so maybe I’m getting the wrong steps.

Thanks,
Carlos.

Hi Carlos,

First of all, good job on developing your own solution. Does it work? If so, it’s valid by definition. We are no clairvoyants, so we cannot know if a solution will ever cause problems. Not even Rick can know if his solutions will cause problems. If they do, he will have to fix them, just like you. Don’t worry too much about that.

A little tip: GetComponent is an expensive method. Instead of calling it each frame, you could cache the reference to the Mover object. See what you did in the Start method in the Mover class.

Keep up the good work! :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms