- Home /
How to stop the attack function if player leaves the check sphere?
The AI will find the player and once within range, attack. If the player leaves the attack range, the AI continues the shoot animation and just slides along the ground. I would like the AI to stop the attack and go back to chase. hey, I got this far with out asking a question.
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
public NavMeshAgent agent;
public Transform player;
public Transform alienBulletSpawn;
private float damage = 10;
public LayerMask whatIsGround, whatIsPlayer;
private Animator anim;
//States
public float attackRange;
public bool playerInAttackRange;
private void Awake()
{
player = GameObject.Find("Player").transform;
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
}
private void Update()
{
anim.SetFloat("Speed", 1f);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInAttackRange) EngagePlayer();
if (playerInAttackRange) AttackPlayer();
}
void EngagePlayer()
{
agent.SetDestination(player.position);
}
void AttackPlayer()
{
agent.SetDestination(transform.position);
transform.LookAt(player);
anim.SetTrigger("Attack");
RaycastHit hit;
if (Physics.Raycast(alienBulletSpawn.transform.position, alienBulletSpawn.transform.forward, out hit))
{
PlayerHealth playerHealth = hit.transform.GetComponent<PlayerHealth>();
if (playerHealth != null)
{
playerHealth.PlayerDamage(damage);
}
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
Answer by Captain_Pineapple · Apr 21 at 09:08 PM
Well your animator has 2 states. Something for your walk animation and something for your attack animation. You currently change from one into the other when you "attack" by setting the trigger "Attack".
Now you simply need a state transition in your animator from the attack animation back to the walk animation. Add another trigger, smth like "StartWalk" and set the attack -> walk transition to trigger when "StartWalk" is set. Then add this call to your EngagePlayer
function:
anim.SetTrigger("StartWalk");
DANG IT! I knew it would be simple but I just could not wrap my head around it. I thank you for your input. I will try it now.
So, I added anim.SetFloat(Speed, 1f); EngagePlayer and he still just stands there and shoots. I will keep trying.
Ok, so the code suggestion works, I just have to sort out some transition stuff in the animator. Thank you very much.
Your answer

Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How to get my navmeshagents to do certain things? 0 Answers
AI Field of vision 1 Answer
Make player not be seen by AI, when player in foilage and shadows. 1 Answer