I have a little code in the update of a cube that I think should make the cube rotate to a “goal” position. However, when activated (when isHolding = false), the cubes snap back to their original spot, and the two QUaternion.identitys remain unequal.
I’m very confused by rotations, I think! Any thoughts on where I go wrong?
var rotation = Quaternion.identity;
var toRotation = Quaternion.identity;
toRotation.eulerAngles = Vector3(goalX, goalY, 0);
if (rotation != toRotation && !controllerObject.GetComponent(controller).isHolding)
{
transform.rotation = Quaternion.Lerp(rotation, toRotation, Time.deltaTime);
if (name == "Puzzle Cube1")
{
print ("Should be adjusting: " + rotation + " | " + toRotation);
}
}
Let me start with the fix. Line 6 ‘should’ be:
transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, Time.deltaTime);
Why it works:
This code is not using Lerp the ‘correct’ way. Lerp is designed to linearly interpolate between two points/values/rotations. The final parameter typically would start at 0 and climb to 1. Instead this code passes approximate the same value each frame since deltaTime is fairly constant. But since we update the start rotation each frame, the total rotation is shrinking. The result is code that moves approximately the same percentage each frame. Since the total amount of the rotation is decreasing, the same percentage represents an ever decreasing amount of rotation, resulting in a eased stop at the end of the rotation.
You code did not work, because you were passing in the same value as the first parameter each frame, so the code was stuck going the same small percentage towards the goal each frame. You can make you code work in another way. Create a timer and pass a fractional amount of the time used as the last parameter.