Smooth Enemy LookRotation

I have a comment in my code that Nathan mentioned smoothing the FacePlayer() code. I’d like to do this and I even went to the final commit files and don’t see that he ever came back to this. I assume it is done with Lerp or Slerp or something. Any guidance there?

There are several options for this:

Quaternion.Lerp(Quaternion from, Quaternion to, float time);
Quaternion.Slerp(Quaternion from, Quaternion to, float time);
Quaternion.RotateTowards(Quaternion from, Quaternion to, float maxAngle);

and you could also use the euler angles and use the Vector3 versions, although you lose some precision.

All of these require multiple frames, which should be ok, because I see FacePlayer is being called in the state’s Tick

1 Like
    protected void FacePlayer()
    {
        if (stateMachine.Player == null) return; //Cancel if no target.

        Vector3 lookPos = stateMachine.Player.transform.position - stateMachine.transform.position; //Find the difference between target and player.
        lookPos.y = 0; //Ignore Y

        stateMachine.transform.rotation = Quaternion.LookRotation(lookPos); //TODO Face target. SMOOTH
    }

That’s what we have for it… So just take in the deltaTime from the state and instead of setting the lookPos use the enemy’s position for from and player position for to then deltaTime? For lerp and slerp? And what is the difference?

Yes, you can get deltaTime like you did for Move.

Lerp is a linear interpolation, while Slerp is spherical. But slerp is a little strange because it interpolates on a sphere centered at the world origin.

See this:

Thanks!

Yeah I was just talking to Brian on another thread about camera zoom. I ended up just making a coroutine to smoothly zoom in and out. I assume it is no more expensive than lerping, right? Lerp is just a behind the scenes CoRoutine in essence.

Well, no. Lerp just returns a single value: the value between a and b at position t. You have to call it continuously with a different t. It doesn’t do any coroutines.

But yes, there’s a specific time when coroutines are executed in the game loop. You can see it here (it’s in the Game Logic section).

I use coroutines all the time. I find it easier than trying to manage timers in the Update.

1 Like

OH… Yeah weird. I guess people do lerp in Update or something and I didn’t notice.

I was pretty proud of my camera zoom script. It adjusts the radius of all 3 orbiting virtual cameras for the free look state. I felt dirty CoRoutining it up just to make it smooth… but it works like a charm and I have some decent checks to stop you from going in or out too far and to not let you spam it while the CoRoutine from the previous mousewheel move is running.

1 Like

This doesn’t mean it’s the right or better thing to do. It’s just something I do.

1 Like

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

Privacy & Terms