1

Hi so what im trying to create is the player can right click on an enemy and he will follow at a certain distance. which is working fine. but what i want it to also do is stop at that distance too. currently if the enemy stops he will try and go to its exact position instead of stopping a little bit away this is what i have currently.

     using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 public class Attacking : MonoBehaviour {
     NavMeshAgent agent;
     Transform target;
     public float distance;
     public float followDistance;
     // Use this for initialization
     void Start () {
         agent = GetComponent<NavMeshAgent>();
     }

     // Update is called once per frame
     void Update () {
         if (Input.GetMouseButton(0))
         {
             target = null;
         }
             if (Input.GetMouseButton(1))
         {
             RaycastHit hit;

             if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
             {
                 if (hit.collider.gameObject.tag == "enemy" || hit.collider.gameObject.tag == "Player")
                 {
                     target = hit.collider.transform;
                 }

             }
         }
         if(target != null)
         {
             distance = Vector3.Distance(transform.position, target.position);
             if (followDistance <= distance)
                 agent.destination = target.position;
         }
     }
 }
pvtctrlalt
  • 61
  • 2
  • 9

1 Answers1

2

Attach a script to your enemy and give it a certain radius ,say 3f.

public float radius=3f;

for better understanding and visual aid use OnDrawGizmosSelected() (on your enemy script).

void OnDrawGizmosSelected ()
{
Gizmos.color=Color.yellow;
Gizmos.DrawWireSphere(transform.position,radius);

}

Now,on your player script use agent.StoppingDistance() as:

if(target != null)
     {
         distance = Vector3.Distance(transform.position, target.position);
         if (followDistance <= distance){
             agent.destination = target.position;
             agent.StoppingDistance=target.radius;
            }


     }

Note:you will have to change target from transform to an instance of your player

SynAck
  • 427
  • 5
  • 19