Guard behaviour: Make guards face the direction they were facing originally?

I believe I bit more than I can chew, or I’m overcomplicating stuff. The guard behaviour as taught in this lesson ends up with the guards facing the wall or anyway away from the player after they return to their post, which looks kinda silly.
I tried to store their rotation at the beginning as a Quaternion, then reapplying it to the Transform in GuardBehaviour, but it doesn’t work. Any hint on what I should look at to figure it out?

private void GuardBehaviour()
        {
            if (transform.position != _guardPosition)
            {
                _mover.StartMoveAction(_guardPosition);
            }
            else if (transform.rotation != _guardPosDirection)
            {
                transform.Rotate(_guardPosDirection.eulerAngles);
            }
        }

So far I figured out that apparently the issue is that guards never REALLY go back to their actual original position, it’s always off by some decimal points, so the else is never triggered.

For the if statement, consider how we decide if the enemy is close enough to the player in the first place… using Vector3.Distance. You’re quite right, the enemy will never arrive at the exact same spot, as we’re dealing with floats, we have to have an “acceptance radius”… usually around 1 meter.
if(Vector3.Distance(transform.position, _guardPosition)>1.0f)

For the rotation, a similar issue exists in terms of the equality check never being precise, but you can simply say
else transform.rotation = _guardPosDirection; and it should work fine.

1 Like

It works, thanks!
There is still a little bug, in that the rotation is on occasion applied a few seconds before the guard stops moving, but overall it’s not a major deal, considering that the player should never see it (if they are close enough to see that, the guard should be in their attack state anyway).
I’ll figure it out later if it becomes a problem. I should probably insert a check in Mover to see if he’s still moving or something, but I don’t want my codebase to drift too much from the course’s, at least until I finished it.

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

Privacy & Terms