- Home /
 
Quaternion.Slerp question, rotating back to original
Hello everyone, I simply want to make my gun rotate a bit left while walking to the left. So I thought I can use Quaternion.Slerp, I used Unity's example code :
  var from : Transform;
     var to : Transform;
     var speed = 0.1;
     function LateUpdate () 
     {
     from = myGun.transform;
     if(Input.GetKey("a")){
     myGun.transform.rotation =
           Quaternion.Slerp (from.rotation, to.rotation, Time.time * speed);
     }
     }
 
               I made an empty gameObject, and rotate it a bit left, and I attached it as "to". Now, when I press "a" key, it works weapon rotates to left as soon as it reaches to "to" gameObject's rotation, but when I released "a" key, it suddenly rotates to it's original rotation, I want it to rotate to it's original rotation slowly and smoothly. In summary, what I want is, my gun will rotate left slowly when I press "a" , but then when I stopped pressing "a" key, gun will rotate to it's original rotation slowly, how can I do that ? Thanks :)
Answer by DaveA · Mar 15, 2012 at 08:36 PM
 if(Input.GetKey("a")){
 myGun.transform.rotation =
       Quaternion.Slerp (from.rotation, to.rotation, Time.time * speed);
 }
 else
     myGun.transform.rotation =
       Quaternion.Slerp (to.rotation, from.rotation, Time.time * speed);
 
              Note that if you release the 'a' key before the gun rotates all the way, it will snap to what would have been its final rotation before rotating back. Ins$$anonymous$$d, consider using myGun.transform.rotation as the 'from' argument.
well I tried this, but it does not slowly turns back to it's original, I don't know why but as soon as I released "a" key it goes to original instantly, is it about the code, or can it be about my weapon ?
Now that I notice, you use Time.time which is absolute time since starting, an ever-increasing number. Try Time.deltaTime ins$$anonymous$$d.
I changed the from in the else statement like you said, it worked. But now there is another problem occured. I pressed and hold "a", the gun reached "to" rotation, and I released "a", it went back to original, perfect. But when I press a again, it goes to "to" rotation instanly and when I released "a" it goes to original instantly too, like once it completes reaching slowly, it switches to instant mode, do you have any ideas ?
well, with a little glitch which is about my weapon code and not important, it's working I guess, thanks for the help :).
Your answer