AiLerp - Stopping Agent on detection

I’m trying to create a very basic set of behaviors;

  • Cast a ray
  • When the ray detects the target, stop moving and attack
  • Else, start moving again

I’ve tried using the below code (and variations where I set the AiLerp.speed to 0), but it seems to be quite ‘janky’ - where the process doesn’t seem to consistently work.

Is there a better way to stop/start the agent’s movement?

    private void FixedUpdate()
    {
        if(targetObj != null)
        {
            CastRayAtTarget();
            AttackBehavior();
        }
        else
        {
            StartCoroutine("Sleep", 3f);
        }
        
    }

    private void CastRayAtTarget()
    {
        LayerMask hitLayer = LayerMask.GetMask("Wall", "Object");

        Vector3 toPosition = targetObj.position;
        Vector3 direction = toPosition - transform.position;

        RaycastHit2D hit = Physics2D.Raycast(transform.position, direction.normalized, attackRange, hitLayer);
        Debug.DrawRay(transform.position, direction.normalized * attackRange, Color.cyan, 0.05f);

        if (hit)
        {
            if (hit.transform.gameObject == targetObj.gameObject)
            {
                isAttacking = true;
            }
            else
            {
                isAttacking = false;
            }
        }
        else
        {
            isAttacking = false;
        }
    }

    private void AttackBehavior()
    {
        if (isAttacking)
        {
            //Stop moving
            aiLerp.canMove = false;            
        }
        else
        {
            //Start moving
            aiLerp.canMove = true;
        }
    }

Hi

What part doesn’t consistently work?

Stopping the agent is usually more reliably done using ai.isStopped, though for the AILerp script that is almost equivalent to using canMove. The only difference I think is that with isStopped it will still recalculate its path regularly.

Hey Aron,

Apologies, meant to mark this off as resolved last night - it was to do with my raycasting conflicting with some colliders - completely foolish error on my part.

Thanks for getting back to me