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;
}
}