Enemy not behaving properly

Video: https://youtu.be/N0neQisNWqQ

Enemy gets stuck running in place if I don’t move after he attacks.

Guessing this is the script that’s causing the issue:

public class EnemyChasingSate : EnemyBaseState
{
    private readonly int LocomotionHash = Animator.StringToHash("Locamotion");
    private readonly int SpeedHash = Animator.StringToHash("Speed");

    private const float CrossFadeDuration = 0.1f;
    private const float AnimatorDampTime = 0.1f;
    
    public EnemyChasingSate(EnemyStateMachine stateMachine) : base(stateMachine)
    {
    }

    public override void Enter()
    {
        stateMachine.Animator.CrossFadeInFixedTime(LocomotionHash, CrossFadeDuration); 
      
    }

    public override void Tick(float deltaTime)
    {
      
        
        if (!IsInChaserange())
        {
            stateMachine.SwitchState(new EnemyIdleState(stateMachine));
            return;
        }
        
        else if (IsInAttackRange())
        {
           stateMachine.SwitchState(new EnemyAttackingState(stateMachine)); 
        }
        
        MoveToPlayer(deltaTime);
        
        FacePlayer();
        
        stateMachine.Animator.SetFloat(SpeedHash, 1f,AnimatorDampTime, deltaTime);
    }

    public override void Exit()
    {
       stateMachine.Agent.ResetPath();
       stateMachine.Agent.velocity = Vector3.zero;
    }

    private void MoveToPlayer(float deltaTime)
    {
        if (stateMachine.Agent.isOnNavMesh)
        {
            stateMachine.Agent.destination = stateMachine.Player.transform.position;

            Move(stateMachine.Agent.desiredVelocity.normalized * stateMachine.MovementSpeed, deltaTime);
        }

        stateMachine.Agent.velocity = stateMachine.CharacterController.velocity;
    }

    private bool IsInAttackRange()
    {
        float playerDistanceSqr = (stateMachine.Player.transform.position - stateMachine.transform.position).sqrMagnitude;

        return playerDistanceSqr <= stateMachine.AttackRange * stateMachine.AttackRange;
    }
}

I was actually assisting another student in the Udemy version of the course with this very issue. We spent a lot of time with debugs and traces, and then the student noticed this very issue. This if clause needs a return statement so that the script doesn’t fall through to the MoveToPlayer() line, which is causing the agent and the character to be out of sync with each other.

    else if (IsInAttackRange())
    {
       stateMachine.SwitchState(new EnemyAttackingState(stateMachine)); 
       return; //This should fix it
    }
2 Likes

Thanks again Brian

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

Privacy & Terms