- Home /
Using Quaternion.Slerp() to rotate an NPC.
I'm having some issues with Quaternion.Slerp. I'm trying to simply rotate the NPC to where there player is standing when they are being talked to. Here's what I have for my starting dialogue function.
function StartDialogue() {
//has talked before
hastalked = true;
lookatplayer = (player.transform.position - transform. position).normalized;
lookingRotation = Quaternion.LookRotation(lookatplayer);
transform.rotation = Quaternion.Slerp(transform.rotation, lookingRotation, Time.deltaTime * rotationSpeed);
dialogueHandler.currentNode = dialogueHandler.startingNode;
dialogueHandler.AddText(dialogueHandler.nodes[dialogueHandler.startingNode].text);
dialogueHandler.talking = true;
talking = dialogueHandler.talking;
playerState.istalking = talking;
}
Any help would be great.
Answer by robertbu · Feb 22, 2014 at 11:11 PM
The likely issue is that StartDialogue() is called only once. Quaternion.Slerp() is intended to be called over multiple frames. One solutions is to move line 9 into Update(). You might have to initialize lookingRotation in Start(). So Start() and Update() have at a minimum:
function Start() {
lookingRotation = transform.rotation;
}
function Update() {
transform.rotation = Quaternion.Slerp(transform.rotation, lookingRotation, Time.deltaTime * rotationSpeed);
}
Is there any way i can put this rotation in a coroutine, though? Even just a lerp?
Yes. You could even put it in your StartDialog function. Hee is a bit of untested code putting the rotate in a separate coroutine::
function DoTheRotate(direction : Vector3) {
var lookingRotation = Quaternion.LookRotation(direction);
while (Vector3.Angle(transform.forward, direction) > 0.5) {
transform.rotation = Quaternion.Slerp(transform.rotation, lookingRotation, Time.deltaTime * rotationSpeed);
yield;
}
}
You would call it by:
DoTheRotate(lookatplayer);
The 0.5 will need to be adjusted for your situation. Because of the way Slerp() works used this way, it can take a really long time to reach the destination rotation, but it can get close quickly. That is why I have Vector3.Angle().
I'm back again- trying to figure out how to change the rotation so that after the NPC dialogue has finished they go back to their original rotation. Any idea?
Just save your 'transform.forward' when you start the dialog, then you can call DoTheRotate() with this vector after the dialog is finished.
Your answer
![](https://koobas.hobune.stream/wayback/20220613134413im_/https://answers.unity.com/themes/thub/images/avi.jpg)