- Home /
Rotating a rigid body to face left or right smoothly
Hi, I'm trying to get my rigid body character to face either left or right but with a smooth movement. I can make it turn instantly with the following code;
if (rigidbody.velocity.x>0.05){
transform.rotation.y=0;
}
if (rigidbody.velocity.x<-0.05){
transform.rotation.y=180;
}
But how can I make it so that it rotates around the y axis over the course of about half a second, instead of instantly snapping to either 0 or 180 degrees?
I have tried using Quaternion.Slerp but wasn't too sure what I was doing with it and not even sure if that's the right method.
Oh and in case it makes a difference, the rigid body character that I want to rotate is fixed on the z plane.
Any help is much appreciated! Thanks.
Answer by Meltdown · Mar 31, 2011 at 04:03 PM
You can use a combination of Quarternion.LookRotation and Slerp to rotate your object to a certain point in space over time...
Something like this...
public GameObject targetPosition;
void Update () {
var targetPoint = targetPosition.transform.position;
var targetRotation = Quaternion.LookRotation(targetPoint - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
}
Where targetPosition is the point in space you want to turn your object to.
Is the best way to do this by using two empty game objects at positions (1000,0,0) and (-1000,0,0) that the character looks at or can it be made to slowly rotate the character to 180 degrees ins$$anonymous$$d of facing a point way of in the distance?
Answer by Jesse Anders · Mar 31, 2011 at 04:27 PM
Note also that you're treating Transform.rotation as a set of angles, but it's actually a quaternion. Because of the way Unity handles things internally, assigning 180 to rotation.y coincidentally has the effect of a 180-degree rotation about the y axis. However, this is pure happenstance; the elements of a quaternion are not angles, and assigning angles to them will produce more or less random results (although as you've found, the results may accidentally turn out to be correct in some cases :)
Ahh yes, I noticed that after playing with this. Thanks for the heads up