- Home /
Incorrect script for slerp rotation
Take a look at this video for a visual description of my problem: http://www.youtube.com/watch?v=Sz_vYC7VdRE
The script chooses the closest cube and then rotates the turret dome towards the selected cube. On the video you can see me clicking on the cube (removing the cube) so the turret will turn towards another cube.
Note that the rotation is limited to the y-axis. The thing is - there are two possible ways to rotate towards an object - the shorter and the longer (except if you are facing opposite direction in which case the left turn and the right turn are the same length). As you can see in the video, the turret choses the wrong (longer) turn when only one cube remains and I can't figure out why.
Here is the code. I am a total newb with these transformations so this is probably the bad way to do such a thing (obviously) - but what I'd like to know is what needs to be changed in my code so that the turning will still be constrained to y-axis but the rotation will happen always the shorter way?
EDIT (with code updated): I have found out that it happens because the destination vector3 is (0,0,0) so slerping from (0,x,0) to (0,0,0) interpolates from x to 0, not taking in account the periodicity of the angles. But I wish there's a simple way to rotate towards the object by rotating the smallest possible angle.
Box closest = FindClosestBox();
if (closest != null) { Vector3 previousRotation = new Vector3(TurretDome.eulerAngles.x, TurretDome.eulerAngles.y, TurretDome.eulerAngles.z); TurretDome.LookAt(closest.transform); Vector3 destinationRotation = new Vector3(0, TurretDome.eulerAngles.y, 0); Vector3 stepRotation = Vector3.Lerp(previousRotation, destinationRotation, RotationSpeed * Time.deltaTime); TurretDome.eulerAngles = stepRotation; }
Thanks in advance.
Answer by Mike 3 · Feb 17, 2011 at 07:40 PM
You should be using Quaternion.Slerp or Quaternion.RotateTowards instead of Vector3.Lerp/Slerp/AnythingVectory
Vector3 offset = closest.transform - transform; offset.y = 0; //clamp it to y rotation only Quaternion lookAt = Quaternion.LookRotation(offset);
transform.rotation = Quaternion.RotateTowards(transform.rotation, lookAt, RotationSpeed * Time.deltaTime);
//OR
transform.rotation = Quaternion.Slerp(transform.rotation, lookAt, RotationSpeed * Time.deltaTime);
RotateTowards will go at a fixed speed in degrees per second, Slerp will be a fairly exponential decay movement
Just a few $$anonymous$$utes before your answer, I stumbled upon a solution on some Youtube tutorial. Thanks anyway. It had to be something simple :)