# Guard Behaviour : Rotate to Initial Position - My Solution

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 (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.

3 Likes

Try Slerping for smoother rotation

``````void OnTriggerEnter(Collider other)
{
// Store the collider information only if it has a CombatTarget component
CombatTarget target = other.GetComponent<CombatTarget>();
if (target != null)
{
combatTarget = target;
}
}

void OnTriggerExit(Collider other)
{
// Reset the combatTarget only if it's the current target
CombatTarget target = other.GetComponent<CombatTarget>();
if (target == combatTarget)
{
combatTarget = null;
}
}
``````