How can i add movement range to my enemy script ?
hi im really new to unity so i would like to know how can i add movement range to my enemy im using the following script
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;
public class NewBehaviourScript : TargetScript { public Animator animator; public float health = 100; public NavMeshAgent navMeshAgent;
bool isDead;
float coolDown = 0.5f;
Transform target;
public GameObject deadEffect;
// Start is called before the first frame update
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
void Update()
{
if (navMeshAgent.remainingDistance < 2 && !isDead)
{
animator.SetTrigger("Attack");
}
if (isHit && coolDown <= 0 && !isDead)
{
Debug.Log("Hit");
health -= 10;
coolDown = 0.5f;
if (health <= 0)
{
animator.SetTrigger("Dead");
navMeshAgent.isStopped = true;
isDead = true;
StartCoroutine(Dead());
}
else
{
animator.SetTrigger("Hurt");
navMeshAgent.isStopped = true;
}
isHit = false;
}
else if (coolDown <= 0)
{
if (!isDead)
{
navMeshAgent.isStopped = false;
navMeshAgent.SetDestination(target.position);
}
}
if (coolDown > 0)
{
coolDown -= Time.deltaTime;
}
}
IEnumerator Dead()
{
yield return new WaitForSeconds(0.5f);
GameObject _effect = Instantiate(deadEffect, transform.position, Quaternion.identity);
Destroy(_effect, 3f);
Destroy(gameObject);
}
}
Answer by zORg_alex · Oct 17, 2021 at 10:50 AM
else if (coolDown <= 0)
{
if (!isDead && Vector3.Distance(target.position, transform.position) < 10f)
{
navMeshAgent.isStopped = false;
navMeshAgent.SetDestination(target.position);
} else
navMeshAgent.Stop();
}
I guess this way. You should declare some stop distance field and use it instead of 10.
So every frame you are setting agents target and make it not stop... This is funny, like you push it with a whip every frame ))) stop this. He also have feelings... May be. I'd do a state bool, like
public bool chasing;
And when
if (!chasing && Vector3.Distance(target.position, transform.position) < ChaseDistance)
set it true and start chasing by setting agents target.
And check to stop chasing like
if (chasing && Vector3.Distance(target.position, transform.position) > ChaseDistance)
set chasing false and make agent stop. This way it will do these things only once that distance get crossed, instead of every frame.
Or did you wanted it to stop from wandering too far from it's origin?
Your answer
Follow this Question
Related Questions
Detect direction of enemy with MoveTowards 1 Answer
How do i stop my enemy from not colliding? 1 Answer
Enemy AI movement Problems 1 Answer
Making a Box Collider sword do Damage 0 Answers