Initially, I wanted to refactor the “InAttackRangeOfPlayer()” bool function to take a float and Vector 3 argument and rename it “InRange” like this
bool InRange(Vector3 position,float range)
{
float distanceToPlayer = Vector3.Distance(transform.position, position);
return distanceToPlayer < range;
}
This way we can repurpose the function to calculate any distance from any position. However, I didn’t know if this function will be used in a future lecture and decided to duplicate and rename it instead
bool InGuardingRange()
{
float distanceToPlayer = Vector3.Distance(transform.position, guardPosition);
return distanceToPlayer < 0.1f;
}
In the Update, If/else statement I simply added this
void Update()
{
if (health.IsDead()) return;
if (InAttackRangeOfPlayer() && fighter.CanAttack(player))
{
fighter.Attack(player);
}
else
{
mover.StartMoveAction(guardPosition);
if (InGuardingRange())
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, guardRotation, 5);
}
}
}
if (InGuardingRange())
{
transform.rotation = Quaternion.RotateTowards(transform.rotation, guardRotation, 5);
}
I made a new Quaternion guardRotation and cached the initial rotation in Start with " guardRotation = transform.rotation; "
By using Quaternion.RotateTowards we can smoothly rotate back to the initial position and make it look more natural.